当前位置: > > > > “被 CORS 政策阻止”,但标头存在
“被 CORS 政策阻止”,但标头存在
来源:stackoverflow
2024-05-01 14:00:38
0浏览
收藏
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《“被 CORS 政策阻止”,但标头存在》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
我使用 go 和 fasthttp 创建了一个 rest api,并使用 vue 创建了一个前端。每次发出 api 请求时,我都会收到错误 access to xmlhttprequest at 'http://localhost:55555/auth/login' from origin 'http://localhost:8080' has been returned by cors policy: no 'access- control-allow-origin' 标头出现在我的浏览器控制台中请求的资源 上。我唯一一次没有收到此错误的是 /auth/check 路线。我还向后端发出了一个 options-request 并获取了所有 cors 标头。如果我发出 post 或 get 请求,我不会收到它们,但我不知道为什么。
后端:
webrouter := router.new()
auth := webrouter.group("/auth")
auth.get("/check", authcheck)
auth.post("/login", authlogin)
auth.get("/logout", authcheck)
err = fasthttp.listenandserve(":"+port, func (ctx *fasthttp.requestctx) {
ctx.response.header.set("access-control-allow-origin", "*")
ctx.response.header.set("access-control-allow-headers", "authorization, content-type, set-cookie, cookie, server")
ctx.response.header.set("access-control-allow-methods", "post, get, options")
ctx.response.header.set("access-control-allow-credentials", "false")
webrouter.handler(ctx)
})
if err != nil {
panic(err)
}
前端请求:
axios.create({
baseURL: 'http://localhost:55555'
}).post('/auth/login', {
email: this.email,
password: this.password
}).then(response => {
console.log(response)
}).catch(err => {
console.log(err)
})
解决方案
我解决了我的问题。我再次阅读了 fasthttp 的文档,发现 ctx.Error() 方法会清除所有标头。相反,我现在手动设置响应代码和错误消息,一切正常。
终于介绍完啦!小伙伴们,这篇关于《“被 CORS 政策阻止”,但标头存在》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~米云公众号也会发布Golang相关知识,快来关注吧!
