无法使用axios发送cookie

huangapple go评论74阅读模式
英文:

Unable to send cookie with axios

问题

尝试添加{withCredentials: true},但仍然无法将 cookie 发送到后端。

return await axios.post(`${API_URL}/posts/category/${id}`, {
  withCredentials: true
})

Cookie

无法使用axios发送cookie

无法使用axios发送cookie

英文:

Tried adding {withCredentials: true} but still unable to send cookie to backend

return await axios.post(`${API_URL}/posts/category/${id}`, {
  withCredentials: true
})

无法使用axios发送cookie

Cookie

无法使用axios发送cookie

答案1

得分: 1

问题在于你将{ withCredentials: true }对象作为axios.post()的第二个参数发送。该函数的签名

> axios.post(url[, data[, config]])

通常在发送POST请求时,你会想发送一些数据,但如果你真的想跳过它,可以将undefined作为第二个参数传递:

return axios.post(`/posts/category/${id}`, undefined, {
  baseURL: API_URL,
  withCredentials: true,
});

我强烈建议利用Axios创建定制实例并设置方便的默认值的能力

const apiClient = axios.create({
  baseURL: API_URL,
  withCredentials: true,
});

// ...

return apiClient.post(`/posts/category/${id}`); // 更加简单
英文:

The issue is that you're sending the { withCredentials: true } object as the 2nd parameter to axios.post(). The signature for that function is

> axios.post(url[, data[, config]])

Typically with a POST request you'll want to send some data but if you really want to skip it, pass undefined as the 2nd parameter

return axios.post(`/posts/category/${id}`, undefined, {
  baseURL: API_URL,
  withCredentials: true,
});

I highly recommend taking advantage of Axios' ability to create customised instances with convenient defaults

const apiClient = axios.create({
  baseURL: API_URL,
  withCredentials: true,
});

// ...

return apiClient.post(`/posts/category/${id}`); // much easier

答案2

得分: -2

自2020年以来,Chrome对跨域Cookie设置增加了更多烦人的限制,您必须将Cookie的SameSite属性设置为none,否则Chrome将拒绝发送Cookie。此外,如果您设置了SameSite属性,您还必须设置secure属性。

proxy_cookie_path / "/; secure; SameSite=none";
英文:

I found this answer on the Internet, hope it will help you.
Since 2020, Chrome add more annoying restricts to cross domain cookies settings, you must set cookies with SameSite to none, otherwise Chrome will refuse to send cookies. More, if you set SameSite, you must set secure.

proxy_cookie_path / "/; secure; SameSite=none";

huangapple
  • 本文由 发表于 2023年4月4日 11:26:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定