POST 请求中缺少 CORS 标头 Allow-Origin

我知道有很多与 CORS 相关的问题,但我似乎找不到这个问题的答案。


这是我的服务器端 golang 代码(我们正在使用 github.com/rs/cors go 模块):我们基本上有一组需要授权标头的 api 和一些不需要的 api(将结帐与结帐视为访客功能)


allowedOrigins := []string{"http://localhost:3000", "http://localhost:3001"}

//allowedHeaders := []string{"Authorization"}

c := cors.New(cors.Options{AllowedOrigins: allowedOrigins, AllowCredentials: true})

handler := c.Handler(r)

我发现的是以下内容:


// if allowcredentials is set to true, then all non auth requests go through but all auth requests return cors error


// if allowedHeaders: authorization is set then all **authenticated and NON authenticated** POST requests fail. GET works fine for both cases.

更具体地说:当我尝试执行 POST 请求并设置上面的 AllowedHeaders:authorization 选项时,我得到的错误是未设置 AllowedOrigins(??.. 我在 PRE-FLIGHT OPTIONS 响应标头中得到这个)。


如果我评论该行(如您在上面看到的),那么非身份验证请求将完美通过,并且 AllowedOrigins hader 将在 OPTIONS 请求中发回。


森林海
浏览 118回答 1
1回答

月关宝盒

解决它....https://github.com/rs/cors有一个不错的CorsOptions Debug:true。我用它来检查发生了什么,当我硬编码允许授权进入我的服务器时,POST 请求随后抱怨,因为我也在发送内容类型(由客户端(axios)自动发送,我没有' t 指定它).. 并且服务器几乎说“我只识别授权标头”......我添加了Content-Type并且它现在可以工作了!allowedHeaders := []string{"Authorization", "Content-Type"}
打开App,查看更多内容
随时随地看视频慕课网APP