前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >beego解决跨域问题:options请求、axios post请求跨域问题

beego解决跨域问题:options请求、axios post请求跨域问题

作者头像
Happyjava
发布2020-10-16 11:02:49
3.3K0
发布2020-10-16 11:02:49
举报
文章被收录于专栏:Happy的分享

根据网上的资料配置,还是未能解决跨域的问题,错误如下:

代码语言:javascript
复制
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'.

网上的配置如下:

代码语言:javascript
复制
	beego.InsertFilter("/*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
	}))

正确的配置(2020-05-10 依然不能完全解决)

代码语言:javascript
复制
	beego.InsertFilter("/*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		AllowCredentials: true,
	}))

2020-05-10:上面的配置,在碰到options请求的时候,依然还是会提示跨域问题:

代码语言:javascript
复制
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_filter.go

代码语言:javascript
复制
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)
}
复制代码

加了这个配置之后,跨域总算解决了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 正确的配置(2020-05-10 依然不能完全解决)
  • 解决
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档