我正在使用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,但据我所知,在javascript和ajax中有一个选项

withCredentials: true

这将自动将cookie发送到客户端。例如,这个场景也是用passportjs生成的,它在服务器上设置了一个cookie

其他回答

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

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

在尝试了2天之后,在尝试了这里的建议之后,这对我来说是有效的。

表达: Cors: Cors ({origin: "http:127.0.0.1:3000", credentials: true,}) Cookie:确保您的Cookie具有secure: true, sameSite: "None" 前端(反应)

axios.defaults.withCredentials = true; (withCredentials: true不适合我)到您请求cookie的地方以及您发送cookie的地方(GET/POST)

希望这也能帮助到其他人。

这招对我很管用:

首先,我必须使用自定义配置创建一个axios的新实例 然后,我使用该axios实例发出post请求

参见下面的代码:

 const ax = axios.create({
  baseURL: 'yourbaseUrl',
  withCredentials: true,
});

const loginUser = () => { const body ={username:state.values.email, password:state.values.password};
ax.post('/login',body).then(function(response){
return response}).then().catch(error => console.log(error));}

来源: https://www.npmjs.com/package/axios#creating-an-instance

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

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

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

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

在这里你可以读到withCredentials

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