我在golang中创建了一个API。后端和前端运行在不同的服务器上。当我用POSTMAN测试API时,一切正常,我收到包含jwt令牌的cookie,但是当我从前端做请求时,没有收到cookie。
这是处理CORS的中间件:
func corsHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// origin := r.Header.Get("Origin")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5000")
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, Authorization, access-control-allow-origin")
return
}
h.ServeHTTP(w, r)
})
}
以下是cookie生成器:
jwtCookie := &http.Cookie{
Name: "jwtToken",
Secure: false,
HttpOnly: true,
Value: tokenString,
Expires: expiryTime,
}
http.SetCookie(w, jwtCookie)
w.Header().Add("Access-Control-Allow-Credentials", "true")
w.WriteHeader(http.StatusOK)
以下是ajax请求:
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/signin',
data: JSON.stringify({
"username": $('#username').val(),
"password": $('#password').val()
}),
xhrFields: { withCredentials: true },
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(message) {
console.log(message.responseJSON);
}
});
在firefox中,响应头看起来像这样:As you can see in image 1, the cookie is received in header but it is not visible in storage
在chrome中,响应头看起来像:there is no cookie visible in chrome
我被困在这很长一段时间了。任何帮助都是有价值的:)
在您的服务器响应中,将HttpOnly
设置为false并在chrome中,转到控制台并键入document.cookie
。您应该看到服务器设置的cookie。
另一种选择是,将HttpOnly
设置为true。在chrome中,打开开发人员工具,单击Application
选项卡,您应该在Cookies
下看到Storage
。单击Cookies
,您应该看到服务器设置的cookie。
我不得不为所有请求添加w.Header().Add("Access-Control-Allow-Credentials", "true")
,而不仅仅是OPTIONS预检请求,而且事实证明chrome没有在存储中显示cookie,但它存在且按预期工作,后来我检查了firefox并且cookie在存储中可见。