CORS策略:缺少“Access-Control-Allow-Origin”头导致预检请求未通过访问控制检查
一分耕耘,一分收获!既然都打开这篇《CORS策略:缺少“Access-Control-Allow-Origin”头导致预检请求未通过访问控制检查》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
我在后端使用 golang 和 gin-gonic/gin web 框架,在前端使用 react axios。我已经尝试解决它两天了,但我仍然遇到以下相同的错误:
cors policy: response to preflight request doesn't pass access control check: no 'access-control-allow-origin' header is present on the requested resource.
仅当我尝试发送 patch 请求时才会发生此错误,因此该请求需要预检 options 请求,但 get 和 post 一切都按预期工作,它们不运行任何预检检查。
这是我的路由器配置的代码:
package main import ( "book_renting/api" "log" "net/http" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/contrib/cors" "github.com/gin-gonic/gin" _ "github.com/lib/pq" ) func main() { router := gin.default() store := cookie.newstore([]byte("your-secret-key")) store.options(sessions.options{maxage: 60 * 60 * 24}) router.use(cors.default()) router.use(sessions.sessions("sessions", store)) router.use(func(c *gin.context) { host := c.request.header.get("origin") c.writer.header().set("access-control-allow-origin", host) c.writer.header().set("access-control-allow-credentials", "true") c.writer.header().set("access-control-allow-headers", "content-type, authorization") c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options") if c.request.method == "options" { log.println("handling options request") c.abortwithstatus(http.statusnocontent) return } log.println("executing cors middleware") c.next() }) router.post("/login", api.handlelogin) router.get("/logout", api.handlelogout) router.post("/register", api.handleregister) router.get("/getcookie", api.getcookiesession) router.get("/books", api.getbooksapi) router.get("/books/:id", api.bookbyidapi) router.patch("/rent/:id", api.rentbookapi) router.patch("/return/:id", api.returnbookapi) router.run("localhost:3000") }
这是前端:
import axios from 'axios' const url = 'http://localhost:3000' export const loginuser = async (credentials) => await axios.post(`${url}/login`, credentials, {withcredentials: true}) export const logoutuser = async () => await axios.get(`${url}/logout`, {withcredentials: true}) export const registeruser = () => axios.post(`${url}/register`) export const fetchbooks = () => axios.get(`${url}/books`, { withcredentials: true }) export const fetchbookbyid = (book_id) => axios.get(`${url}/books/${book_id}`, { withcredentials: true }) export const rentbook = (book_id) => axios.patch(`${url}/rent/${book_id}`, { withcredentials: true }) export const returnbook = (book_id) => axios.patch(`${url}/return/${book_id}`, { withcredentials: true })
我非常确定我正确设置了后端,它应该返回所有必要的标头。
例如,对于 get 请求,响应标头如下所示:
http/1.1 200 ok access-control-allow-credentials: true access-control-allow-headers: content-type, authorization access-control-allow-methods: get, post, put, delete, patch, options access-control-allow-origin: http://localhost:3001 content-type: application/json; charset=utf-8 date: sat, 10 jun 2023 22:12:11 gmt content-length: 495
虽然对于 patch 请求尝试,我没有任何响应(毫不奇怪),并且预检响应标头是:
http/1.1 200 ok date: sat, 10 jun 2023 22:12:12 gmt content-length: 0
您对可能出现的问题有什么建议吗?经过这两天我已经毫无头绪了。预先感谢您!
我还尝试添加标题:
c.writer.header().set("access-control-allow-origin", host) c.writer.header().set("access-control-allow-credentials", "true") c.writer.header().set("access-control-allow-headers", "content-type, authorization") c.writer.header().set("access-control-allow-methods", "get, post, put, delete, patch, options")
...再次在 if 语句中:
if c.request.method == "options" { log.println("handling options request") c.abortwithstatus(http.statusnocontent) return }
但这根本没有帮助。事实上,这个if语句在执行预检时并没有执行,我从控制台知道服务器正在执行options请求。
[gin] 2023/06/11 - 00:12:13 | 200 | 7.708µs | 127.0.0.1 | options "/rent/2"
编辑:
这是发送 patch 请求的 curl 命令(因此实际上这是预检 options 请求):
curl 'http://localhost:3000/return/2' \ -x 'options' \ -h 'accept: */*' \ -h 'accept-language: en-us,en;q=0.9,pl-pl;q=0.8,pl;q=0.7' \ -h 'access-control-request-headers: content-type' \ -h 'access-control-request-method: patch' \ -h 'cache-control: no-cache' \ -h 'connection: keep-alive' \ -h 'origin: http://localhost:3001' \ -h 'pragma: no-cache' \ -h 'referer: http://localhost:3001/' \ -h 'sec-fetch-dest: empty' \ -h 'sec-fetch-mode: cors' \ -h 'sec-fetch-site: same-site' \ -h 'user-agent: mozilla/5.0 (macintosh; intel mac os x 10_15_7) applewebkit/537.36 (khtml, like gecko) chrome/114.0.0.0 safari/537.36' \ --compressed
对此请求的响应:
HTTP/1.1 200 OK Date: Sun, 11 Jun 2023 01:22:57 GMT Content-Length: 0
正确答案
事实证明,您正在使用已弃用的软件包 github.com/gin-gonic/contrib/cors
。您应该使用 github.com/gin-contrib/cors
代替。这是使用 github.com/gin-contrib/cors
的演示配置:
package main import ( "github.com/gin-contrib/cors" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" ) func main() { router := gin.default() config := cors.defaultconfig() config.addallowheaders("authorization") config.allowcredentials = true config.allowallorigins = false // i think you should whitelist a limited origins instead: // config.allowallorigins = []{"xxxx", "xxxx"} config.alloworiginfunc = func(origin string) bool { return true } router.use(cors.new(config)) store := cookie.newstore([]byte("your-secret-key")) store.options(sessions.options{maxage: 60 * 60 * 24}) router.use(sessions.sessions("sessions", store)) // routes below router.run("localhost:3000") }
由于某种原因,patch
请求标头缺少“cookie”标头,尽管我使用了 withcredentials
参数。
axios.patch(`${url}/rent/${book_id}`, { withcredentials: true })
这里 { withcredentials: true }
被视为数据,并且没有配置。如果你没有数据发送到服务器,你应该这样写:
axios.patch(`${url}/rent/${book_id}`, null, { withCredentials: true })
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

- 上一篇
- 能否终止未完成的 goroutine?

- 下一篇
- 使用Go:一次性对多个结果进行解码实现ManyDecode
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 毕业宝AIGC检测
- 毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
- 20次使用
-
- AI Make Song
- AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
- 31次使用
-
- SongGenerator
- 探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
- 28次使用
-
- BeArt AI换脸
- 探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
- 31次使用
-
- 协启动
- SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
- 34次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览