axios 携带cookie_使Axios自动在其请求中发送cookie

在客户端使用 Axios 向 Express.js 服务器发送请求时,遇到无法读取到设置的 Cookie 问题。尝试通过 `req.headers` 和 `req.cookies` 访问但未成功。已安装 cookie-parser 中间件。解决方案在于设置 Axios 的 `withCredentials` 属性为 `true`,以允许跨域请求携带 Cookie。
摘要由CSDN通过智能技术生成

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

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 => ...

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

req.headers

req.cookies

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

app.use(cookieParser())

How do I make Axios send cookies in requests automatically?

Edit:

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

}

})

}

...

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.

解决方案

I had the same problem and fixed it by withCredential property.

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('some api url', {withCredentials: true});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值