【发布时间】:2020-08-25 06:05:58
【问题描述】:
我正在尝试在 Go 中设置一个 cookie。当我运行我的代码时,我在浏览器中收到一个 CORS 错误,说明 Access-Control-Allow-Credentials 设置为空且必须为真。但是,在我的代码中,它设置为 true。你知道可能是什么问题吗?
CORS 错误
Access to fetch at 'http://127.0.0.1:8000/signup' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
Go 代码 sn-ps
func signup(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == http.MethodOptions {
return
}
}
r := mux.NewRouter()
header := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Origin"})
methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"})
origin := handlers.AllowedOrigins([]string{"http://127.0.0.1:8080"})
r.HandleFunc("/signup", signup).Methods("POST", "OPTIONS")
log.Fatal(http.ListenAndServe(":8000", handlers.CORS(header, methods, origin)(r)))
客户端JS
fetch(`${URL_API}/signup`, {
method: 'post',
credentials: 'include',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then((data) => console.log(data))
.catch(function (error) {
console.log('Request failed', error);
});
【问题讨论】:
-
localhost和127.0.0.1不是同一个主机,因此它将其视为跨域请求。 -
@Adrian 抱歉,现在都是 127.0.0.1 已更新帖子。仍然出现错误。谢谢!
-
在您拨打
handlers.AllowedOrigins(…)的地方,您是否尝试过添加handlers.AllowCredentials(true)? github.com/rs/cors#parameters
标签: go cookies cross-domain