我使用 Go 和 fasthttp
创建了一个 REST API和一个使用 Vue 的前端。每次我发出 API 请求时,都会收到错误 Access to XMLHttpRequest at 'http://localhost:55555/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
在我的浏览器控制台中。我唯一没有收到此错误的是 /auth/check
路线。我还向我的后端发出了一个 OPTIONS-Request 并获得了所有的 CORS header 。如果我发出 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()
方法清除所有标题。相反,我现在手动设置响应代码和错误消息,一切正常。
关于javascript - “被 CORS 策略阻止”,但存在 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221927/