beego解決跨域問題:options請求、axios post請求跨域問題

根據網上的資料配置,仍是未能解決跨域的問題,錯誤以下:跨域

has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. 複製代碼

網上的配置以下:bash

beego.InsertFilter("/*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
	}))
複製代碼

正確的配置(2020-05-10 依然不能徹底解決)

beego.InsertFilter("/*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
	}))
複製代碼

2020-05-10:上面的配置,在碰到options請求的時候,依然仍是會提示跨域問題:markdown

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. 複製代碼

等等報錯。cors

解決

既然用這些配置無法解決,那就本身擼一個吧。spa

cors_filter.gocode

var success = []byte("SUPPORT OPTIONS")

var corsFunc = func(ctx *context.Context) {
	origin := ctx.Input.Header("Origin")
	ctx.Output.Header("Access-Control-Allow-Methods", "OPTIONS,DELETE,POST,GET,PUT,PATCH")
	ctx.Output.Header("Access-Control-Max-Age", "3600")
	ctx.Output.Header("Access-Control-Allow-Headers", "X-Custom-Header,accept,Content-Type,Access-Token")
	ctx.Output.Header("Access-Control-Allow-Credentials", "true")
	ctx.Output.Header("Access-Control-Allow-Origin", origin)
	if ctx.Input.Method() == http.MethodOptions {
		// options請求,返回200
		ctx.Output.SetStatus(http.StatusOK)
		_ = ctx.Output.Body(success)
	}
}

func init() {
	beego.InsertFilter("/*", beego.BeforeRouter, corsFunc)
}
複製代碼

加了這個配置以後,跨域總算解決了。orm

相關文章
相關標籤/搜索