http - 响应中存在 CORS set-cookie 标头,但未创建 cookie
问题描述
我正在尝试从 Go (127.0.0.1:8080) 中制作的 API 在我的客户端 (127.0.0.1:3000) 中创建一个 cookie,我想我已经在 CORS 所需的响应中添加了大多数标头,并且 cookie 具有相同的站点=none和secure=true但仍未设置。下面我添加了请求和响应的图片,如 chrome devtools 网络选项卡中所示,以及发出请求的 axios 代码和 API 服务器中处理请求的 go 代码。
去:
//Handles account sign ins
func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Println("login handler")
//decoder := json.NewDecoder(r.Body)
//var t models.LoginUserData
//err := decoder.Decode(&t)
//if err != nil {
// log.Println(err)
//}
//middleware.SignIn(t.User.Username, t.User.Password)
http.SetCookie(w, &http.Cookie{Name: "sabor", Value: "merda", Path: "/", HttpOnly: false, SameSite: http.SameSiteNoneMode, Secure: true, Domain: "127.0.0.1"})
header := w.Header()
header.Set("Access-Control-Allow-Credentials", "true")
//header.Set("Access-Control-Expose-Headers", "Set-Cookie")
header.Set("Access-Control-Allow-Headers", "Content-Type, withCredentials")
header.Set("Access-Control-Allow-Origin", "http://127.0.0.1:3000")
header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.WriteHeader(http.StatusOK)
}
爱讯:
let config = {
headers: {
withCredentials: true,
},
};
axios
.post(
"http://127.0.0.1:8080/login",
{
User: {
Username: username,
Password: password,
},
},
config
)
.then(function (response) {
console.log(response)
console.log(response.data)
console.log(response.headers)
console.log(response.data.cookie)
if (response.status === 200) {
console.log("if works")
}
})
.catch(function (error) {
console.log(error);
});
请求和响应图像: 请求和响应图像
解决方案
您将 cookie 标记为“安全”(HTTPS),但是通过不安全 (HTTP) 连接向您的 API 发出请求。
Secure 属性将 cookie 的范围限制为“安全”通道(其中“安全”由用户代理定义)。当 cookie 具有 Secure 属性时,仅当请求通过安全通道(通常是 HTTP over Transport Layer Security (TLS) 传输时,用户代理才会在 HTTP 请求中包含 cookie 请参阅https://www.rfc-editor .org/rfc/rfc6265
你可以在下面试试这个;
func Login(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// In case you don't have separate CORS middleware
if r.Method == http.MethodOptions {
header := w.Header()
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Allow-Headers", "Content-Type, withCredentials")
header.Set("Access-Control-Allow-Origin", "http://localhost:3000")
header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.WriteHeader(http.StatusOK)
return
}
http.SetCookie(w, &http.Cookie{Name: "sabor", Value: "merda", Path: "/", HttpOnly: false, SameSite: http.SameSiteNoneMode, Secure: false, Domain: "localhost"})
}
而从 axios 中,只需将端点替换为 localhost;axios.post("http://localhost:8080/login", ...
推荐阅读
- jquery - jquery获取元素的值
- reactjs - 无法使用 React Router 访问来自 Api 的详细信息,而不会在页面上呈现
- swift - 符合具有关联值的类型的协议
- sql-server - 在 SQL 中透视具有多列的表
- scala - Scala replaceAllIn 无法正常工作?
- sql - 有没有办法选择多行但只返回不同的列?
- android - Andoid webview 自己的服务器
- c - Sorting matrix by even numbers in rows
- colors - Gnuplot 用线条颜色设置绘图
- java - Configure SSL certificate in Angular 8 with Spring boot Application