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


当前回答

//在创建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));

其他回答

另一个解决方案是使用这个库:

https://github.com/3846masa/axios-cookiejar-support

它将“Tough Cookie”支持集成到Axios中。注意,这种方法仍然需要withCredentials标志。

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

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

所以我也有同样的问题,我花了大约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”密钥。

就我而言,问题出在cookie上,而不是Axios;虽然我接收和发送cookie从/到相同的域/子域/主机,我期望它在不同的路径上使用不同的资源-但我的cookie就像我已经设置了一个单一的路径,即使我省略了这个属性。显式地设置Path=/;在饼干里解决了这个问题。

法提赫的答案在2022年仍然有效。

axios.defaults.withCredentials = true也可以做到这一点。

将{withCredentials: true}传递给单独的axios调用似乎不建议使用。