javascript - “被 CORS 策略阻止”,但存在 header

标签 javascript http vue.js go cors

我使用 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/

相关文章:

javascript - 搜索字符串但忽略标签

javascript - C3.js 时间序列图表去除黑色 SVG 填充

http - 如何使用 Behat/Mink 高效地测试访问大文件?

vue.js - 如何清除 vuex store 中的状态?

vue.js - 如何更新 vue cli 版本?

javascript - Bootstrap 轮播 slider 事件类和下一个/上一个按钮不起作用

javascript - 在 GET 之前重新发送 OPTIONS 方法

HTTP 缓存 - 检查服务器,始终发送 If-Modified-Since

rest - HTTP 授权和 WWW-Authenticate header

css - 共享 Vue 组件 : CSS has to be manually imported by the client