英文:
Golang Mux Router CORS Error when Adding Credentials to Request
问题
我只需要在我的Go Mux路由器中允许凭据。这似乎应该很简单。只要我在axios拦截器中将withCredentials
设置为true,我就只会得到CORS错误。然而,我相信我已经正确配置了它。我是否漏掉了什么?
这是我提供路由的地方:
log.Fatal(http.ListenAndServe(":8080",
handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "withCredentials"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowCredentials())(loggedRouter)))
显然,我需要启用此功能以设置和获取cookie。我尝试以以下方式设置cookie:
//设置会话cookie
http.SetCookie(w, &http.Cookie{
Name: "session_key",
Value: staffAdminSession.SessionKey,
Expires: time.Now().Add(time.Hour * 24),
HttpOnly: true,
})
它在Postman中设置,但在Chrome中没有设置。这一定是一个CORS/请求头问题。
英文:
I simply need to allow for credentials in my Go Mux router. It seems like it should be pretty straight forward. As soon as I set withCredentials
to true in my axios interceptor, I only get CORS errors. However, I believe I configured it correctly. Is there something I'm missing?
Here's where I serve the routes:
log.Fatal(http.ListenAndServe(":8080",
handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "withCredentials"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowCredentials())(loggedRouter)))
Obviously, I need to enable this to set and get cookies. I attempt to set the cookie this way:
//set session cookie
http.SetCookie(w, &http.Cookie{
Name: "session_key",
Value: staffAdminSession.SessionKey,
Expires: time.Now().Add(time.Hour * 24),
HttpOnly: true,
})
It sets in postman, but not in Chrome. It must be a CORS/request header issue.
Here's all the information I'm given for the error - the status of the request is CORS Error:
答案1
得分: 2
你应该在控制台中检查错误消息。应该会有一个类似这样的错误消息:
> 由于 CORS 策略的限制,从源 'http://localhost:8080' 访问 'http://0.0.0.0:8081/login' 的请求已被阻止:当请求的凭据模式为 'include' 时,响应中的 'Access-Control-Allow-Origin' 标头的值不能是通配符 '*'。
截图显示源为 http://0.0.0.0:3000
,尝试将以下代码:
handlers.AllowedOrigins([]string{"*"}
替换为:
handlers.AllowedOrigins([]string{"http://0.0.0.0:3000"}
英文:
You should check the error message in the console. There should be an error message like this:
> Access to fetch at 'http://0.0.0.0:8081/login' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The screenshot shows that the origin is http://0.0.0.0:3000
, try replacing
handlers.AllowedOrigins([]string{"*"}
with:
handlers.AllowedOrigins([]string{"http://0.0.0.0:3000"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论