英文:
Unable to send cookie with axios
问题
尝试添加{withCredentials: true}
,但仍然无法将 cookie 发送到后端。
return await axios.post(`${API_URL}/posts/category/${id}`, {
withCredentials: true
})
Cookie
英文:
Tried adding {withCredentials: true}
but still unable to send cookie to backend
return await axios.post(`${API_URL}/posts/category/${id}`, {
withCredentials: true
})
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";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论