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

相关文章
相关标签/搜索