![](/img/trans.png)
[英]localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]'Blocked by CORS policy', but Header is present
我使用 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
在我的瀏覽器控制台中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 標頭。 如果我發出 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()
方法會清除所有標頭。 相反,我現在手動設置響應代碼和錯誤消息,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.