让 Axios 在其请求中自动发送 cookie

2022-01-30 00:00:00 axios node.js express cookies javascript

我正在使用 Axios 从客户端向我的 Express.js 服务器发送请求.

I am sending requests from the client to my Express.js server using Axios.

我在客户端设置了一个 cookie,我想从所有 Axios 请求中读取该 cookie,而不是手动将它们添加到手动请求中.

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.

这是我的客户端请求示例:

This is my clientside request example:

axios.get(`some api url`).then(response => ...

我尝试通过在我的 Express.js 服务器中使用这些属性来访问标头或 cookie:

I tried to access headers or cookies by using these properties in my Express.js server:

req.headers
req.cookies

它们都不包含任何 cookie.我正在使用 cookie 解析器中间件:

Neither of them contained any cookies. I am using cookie parser middleware:

app.use(cookieParser())

如何让 Axios 在请求中自动发送 cookie?

How do I make Axios send cookies in requests automatically?

我在客户端这样设置cookie:

I set cookie on the client like this:

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:'/'})
        }
      })
    }
...

虽然它也在使用 Axios,但它与问题无关.一旦设置了 cookie,我只想将 cookie 嵌入到我的所有请求中.

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.

推荐答案

你可以使用 withCredentials 属性.

You can use withCredentials property.

来自不同域的 XMLHttpRequest 无法为自己的域设置 cookie 值,除非在发出请求之前将 withCredentials 设置为 true.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

axios.get(BASE_URL + '/todos', { withCredentials: true });

还可以对每个 Axios 请求强制提供凭据

Also its possible to force credentials to every Axios requests

axios.defaults.withCredentials = true

或者使用一些Axios请求的凭证,如下代码

Or using credentials for some of the Axios requests as the following code

const instance = axios.create({
   withCredentials: true,
   baseURL: BASE_URL
})
instance.get('/todos')

相关文章