使Axios自动在其请求中发送cookie [英] Make Axios send cookies in its requests automatically

查看:4431
本文介绍了使Axios自动在其请求中发送cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在客户端上设置了一个cookie,我想从所有Axios请求中读取该cookie,而不是手动添加它们来手动请求。

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

我试图访问标题或者在我的Express.js服务器中使用这些属性的cookie:

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

req.headers
req.cookies

它们都不包含任何cookie。我使用的是cookie解析器中间件:

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

app.use(cookieParser())

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

How do I make Axios send cookies in requests automatically?

编辑:

我在客户端设置cookie像这样:

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

虽然它也使用Axios,但它与问题无关。一旦设置了cookie,我只想在我的所有请求中嵌入cookie。

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.

推荐答案

我遇到了同样的问题并通过 withCredential 属性。

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

来自其他域的XMLHttpRequest无法设置cookie值对于他们自己的域,除非在提出请求之前将withCredentials设置为true。

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

这篇关于使Axios自动在其请求中发送cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆