我正在使用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嵌入到所有请求中。


当前回答

在package.json(Frontend)中设置代理,并重新启动服务器(问题解决)

其他回答

对于那些仍然无法解决这个问题的人,这个答案帮助了我。 Stackoverflow回答:34558264

TLDR; 我们需要在两个axios的GET请求和POST请求(获取cookie)以及fetch中设置{withCredentials: true}。

你把两种想法混在一起了。

有react-cookie和axios

React-cookie =>用于在客户端处理cookie

Axios =>用于向服务器发送ajax请求

有了这些信息,如果您希望来自客户端的cookie也能在后端进行通信,则需要将它们连接在一起。

来自"react-cookie" Readme的注释:

同构饼干! 为了能够在执行服务器呈现时访问用户cookie,您可以 可以使用plugToRequest或setRawCookie。

链接到readme

如果这是你需要的,很好。

如果没有,请评论,以便我可以详细说明。

TL; diana:

{withCredentials: true}或axios.defaults.withCredentials = true


来自axios文档

withCredentials: false, //默认

withCredentials指示是否应该使用凭据进行跨站点访问控制请求

如果你传递{withCredentials: true}与你的请求,它应该工作。

更好的方法是在axios.defaults中将withCredentials设置为true

axios.defaults.withCredentials = true

对我有用的是:

客户端:

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',
  })
);

//在创建axios实例时使用

const API = axios.create({
    baseURL: "http://localhost:4000", // API URL
    withCredentials: true,
});

//在后台的app.js中使用这个中间件 首先,安装NPM I cors

var cors = require("cors"); // This should be at the end of all middlewares

const corsOptions = {
    origin: "http://localhost:3000",
    credentials: true, //access-control-allow-credentials:true
    optionSuccessStatus: 200,
};

app.use(cors(corsOptions));