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

我在客户机上设置了一个cookie,我希望从所有Axios请求中读取该cookie,而不需要手动将它们添加到请求中。

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

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

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

req.headers
req.cookies

它们都没有包含任何cookie。我使用cookie解析器中间件:

app.use(cookieParser())

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

编辑:

我在客户端设置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:'/'})
        }
      })
    }
...

虽然它也使用Axios,但它与问题无关。我只是想在设置cookie后将cookie嵌入到所有请求中。


当前回答

您可以使用withCredentials属性在请求中传递cookie。

axios.get(`api_url`, { withCredentials: true })

通过设置{withCredentials: true},您可能会遇到跨起源问题。为了解决这个问题 你需要使用

expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));

在这里你可以读到withCredentials

其他回答

这并不适用于每个人,但我使用了一个React前端与Vite,它正在为localhost 127.0.0.1:5173服务,这是我作为CORS允许域。只要我都到本地主机一切正常工作!

你可以使用withCredentials属性。

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

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

此外,还可以对每个Axios请求强制凭据

axios.defaults.withCredentials = true

或者对某些Axios请求使用凭据,如下面的代码所示

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

所以我也有同样的问题,我花了大约6个小时去寻找,我有

withCredentials:真

但是浏览器仍然没有保存cookie,直到出于某种奇怪的原因,我才想到重新调整配置设置:

Axios.post(GlobalVariables.API_URL + 'api/login', {
        email,
        password,
        honeyPot
    }, {
        withCredentials: true,
        headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
    }});

似乎你应该总是先发送“withCredentials”密钥。

对我有用的是:

客户端:

import axios from 'axios';

const url = 'http://127.0.0.1:5000/api/v1';

export default {
  login(credentials) {
    return axios
      .post(`${url}/users/login/`, credentials, {
        withCredentials: true,
        credentials: 'include',
      })
      .then((response) => response.data);
  },
};

注意:凭证将是post请求的主体,在这种情况下,用户登录信息(通常从登录表单获得):

{
    "email": "user@email.com",
    "password": "userpassword"
}

服务器端:

const express = require('express');
const cors = require('cors');

const app = express();
const port = process.env.PORT || 5000;

app.use(
  cors({
    origin: [`http://localhost:${port}`, `https://localhost:${port}`],
    credentials: 'true',
  })
);

您可以使用withCredentials属性在请求中传递cookie。

axios.get(`api_url`, { withCredentials: true })

通过设置{withCredentials: true},您可能会遇到跨起源问题。为了解决这个问题 你需要使用

expressApp.use(cors({ credentials: true, origin: "http://localhost:8080" }));

在这里你可以读到withCredentials