Javascript 使 Axios 在其请求中自动发送 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43002444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make Axios send cookies in its requests automatically
提问by Kunok
I am sending requests from the client to my Express.js server using Axios.
我正在使用 Axios 从客户端向我的 Express.js 服务器发送请求。
I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.
我在客户端设置了一个 cookie,我想从所有 Axios 请求中读取该 cookie,而不需要手动将它们添加到手动请求中。
This is my clientside request example:
这是我的客户端请求示例:
axios.get(`some api url`).then(response => ...
I tried to access headers or cookies by using these properties in my Express.js server:
我尝试通过在 Express.js 服务器中使用这些属性来访问标头或 cookie:
req.headers
req.cookies
Neither of them contained any cookies. I am using cookie parser middleware:
它们都不包含任何 cookie。我正在使用 cookie 解析器中间件:
app.use(cookieParser())
How do I make Axios send cookies in requests automatically?
如何让 Axios 在请求中自动发送 cookie?
Edit:
编辑:
I set cookie on the client like this:
我像这样在客户端上设置 cookie:
import cookieClient from 'react-cookie'
...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
axios.get('path/to/my/cookie/api').then(response => {
if(response.status == 200){
cookieClient.save('cookie-name', response.data, {path:'/'})
}
})
}
...
While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.
虽然它也在使用 Axios,但它与问题无关。我只想在设置 cookie 后将 cookie 嵌入到我的所有请求中。
回答by fingerpich
I had the same problem and fixed it by using the withCredentialsproperty.
我遇到了同样的问题并通过使用该withCredentials属性修复了它。
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.
来自不同域的 XMLHttpRequest 无法为其自己的域设置 cookie 值,除非在发出请求之前将 withCredentials 设置为 true。
axios.get('some api url', {withCredentials: true});
回答by Fatih Acet
TL;DR:
特尔;博士:
{ withCredentials: true }or axios.defaults.withCredentials = true
{ withCredentials: true }或者 axios.defaults.withCredentials = true
From the axios documentation
来自 axios 文档
withCredentials: false, // default
withCredentials: false, // default
withCredentialsindicates whether or not cross-site Access-Control requests should be made using credentials
withCredentials指示是否应使用凭据发出跨站点访问控制请求
If you pass { withCredentials: true }with your request it should work.
如果您通过{ withCredentials: true }您的请求,它应该可以工作。
A better way would be setting withCredentialsas truein axios.defaults
一个更好的方法将被设置withCredentials为true在axios.defaults
axios.defaults.withCredentials = true
axios.defaults.withCredentials = true
回答by RITESH ARORA
I am not familiar with Axios, but as far as I know in javascript and ajax there is an option
我不熟悉 Axios,但据我所知在 javascript 和 ajax 中有一个选项
withCredentials: true
This will automatically send the cookie to the client-side. As an example, this scenario is also generated with passportjs, which sets a cookie on the server
这将自动将 cookie 发送到客户端。举个例子,这个场景也是用passportjs生成的,它在服务器上设置了一个cookie
回答by Eyk Rehbein
It's also important to set the necessary headers in the express response. These are those which worked for me:
在快速响应中设置必要的标头也很重要。这些是对我有用的:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', yourExactHostname);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
回答by machineghost
Another solution is to use this library:
另一种解决方案是使用这个库:
https://github.com/3846masa/axios-cookiejar-support
https://github.com/3846masa/axios-cookiejar-support
which integrates "Tough Cookie" support in to Axios. Note that this approach still requires the withCredentialsflag.
它将“Tough Cookie”支持集成到 Axios 中。请注意,这种方法仍然需要withCredentials标志。
回答by prak
How do I make Axios send cookies in requests automatically?
如何让 Axios 在请求中自动发送 cookie?
set axios.defaults.withCredentials = true;
放 axios.defaults.withCredentials = true;
or for some specific request you can use axios.get(url,{withCredentials:true})
或者对于某些特定的请求,您可以使用 axios.get(url,{withCredentials:true})
this will give CORS error if your 'Access-Control-Allow-Origin' is set to wildcard(*). Therefore make sure to specify the url of origin of your request
如果您的“Access-Control-Allow-Origin”设置为通配符(*),则会出现 CORS 错误。因此,请确保指定请求的来源网址
for ex: if your front-end which makes the request runs on localhost:3000 , then set the response header as
例如:如果使请求在 localhost:3000 上运行的前端,则将响应标头设置为
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
also set
还设置
res.setHeader('Access-Control-Allow-Credentials',true);
回答by the_dangoria
for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264
对于仍然无法解决它的人,这个答案帮助了我。 stackoverflow 答案:34558264
TLDR;
one needs to set {withCredentials: true}in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.
TLDR;需要{withCredentials: true}在 GET 请求和 POST 请求(获取 cookie)中为 axios 和 fetch 设置。
回答by Luigi Cordoba Granera
So I had this exact same issue and lost about 6 hours of my life searching, I had the
所以我遇到了完全相同的问题并且失去了大约 6 个小时的生命搜索,我有
withCredentials: true
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
但是浏览器仍然没有保存 cookie,直到出于某种奇怪的原因,我想到了调整配置设置的想法:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
似乎您应该始终首先发送“withCredentials”密钥。
回答by Sunil Garg
You can use withCredentialsproperty to pass cookies in the request.
您可以使用withCredentials属性在请求中传递 cookie。
axios.get(`api_url`, { withCredentials: true })
By setting { withCredentials: true }you may encounter cross origin issue. To solve that
you need to use
通过设置,{ withCredentials: true }您可能会遇到跨源问题。要解决您需要使用
expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));
Here you can read about withCredentials
在这里你可以阅读withCredentials
回答by Tzook Bar Noy
You are getting the two thinks mixed.
你让这两种想法混合在一起。
You have "react-cookie" and "axios"
你有“react-cookie”和“axios”
react-cookie => is for handling the cookie on the client side
react-cookie => 用于在客户端处理 cookie
axios => is for sending ajax requests to the server
axios => 用于向服务器发送ajax请求
With that info, if you want the cookies from the client side to be communicated in the backend side as well, you will need to connect them together.
有了这些信息,如果您希望来自客户端的 cookie 也在后端进行通信,则需要将它们连接在一起。
Note from "react-cookie" Readme:
“react-cookie”自述文件中的注释:
Isomorphic cookies!
To be able to access user cookies while doing server-rendering, you can use plugToRequest or setRawCookie.
同构饼干!
为了能够在进行服务器渲染时访问用户 cookie,您可以使用 plugToRequest 或 setRawCookie。
If this is what you need, great.
如果这是您所需要的,那就太好了。
If not, please comment so I could elaborate more.
如果没有,请发表评论,以便我可以详细说明。

