your programing

Axios가 요청에서 자동으로 쿠키를 보내도록합니다.

lovepro 2020. 10. 4. 12:53
반응형

Axios가 요청에서 자동으로 쿠키를 보내도록합니다.


Axios를 사용하여 클라이언트에서 Express.js 서버로 요청을 보내고 있습니다.

클라이언트에 쿠키를 설정하고 수동으로 요청하기 위해 수동으로 추가하지 않고 모든 Axios 요청에서 해당 쿠키를 읽고 싶습니다.

이것은 내 클라이언트 측 요청 예입니다.

axios.get(`some api url`).then(response => ...

Express.js 서버에서 다음 속성을 사용하여 헤더 또는 쿠키에 액세스하려고했습니다.

req.headers
req.cookies

둘 다 쿠키를 포함하지 않았습니다. 쿠키 파서 미들웨어를 사용하고 있습니다.

app.use(cookieParser())

Axios가 요청에서 쿠키를 자동으로 보내도록하려면 어떻게해야합니까?

편집하다:

다음과 같이 클라이언트에 쿠키를 설정합니다.

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도 사용하지만 질문과 관련이 없습니다. 쿠키가 설정되면 모든 요청에 ​​쿠키를 삽입하고 싶습니다.


나는 같은 문제가 있었고 withCredential 속성으로 수정했습니다 .

다른 도메인의 XMLHttpRequest는 요청하기 전에 withCredentials가 true로 설정되어 있지 않으면 자신의 도메인에 대한 쿠키 값을 설정할 수 없습니다.

axios.get('some api url', {withCredentials: true});

Axios에 익숙하지 않지만 javascript와 ajax에서 아는 한 옵션이 있습니다.

withCredentials: true

그러면 자동으로 쿠키가 클라이언트 측에 전송됩니다. 예를 들어,이 시나리오는 서버에 쿠키를 설정하는 passportjs로도 생성됩니다.


빠른 응답에서 필요한 헤더를 설정하는 것도 중요합니다. 다음은 나를 위해 일한 것입니다.

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', yourExactHostname);
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

axios 문서에서

withCredentials : false, // 기본값

withCredentials 자격 증명을 사용하여 교차 사이트 액세스 제어 요청을 만들어야하는지 여부를 나타냅니다.

{ withCredentials: true }요청 을 통과 하면 작동합니다.

더 나은 방법은 다음 withCredentials과 같이 설정 하는 것 true입니다.axios.defaults

axios.defaults.withCredentials = true


Another solution is to use this library:

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

which integrates "Tough Cookie" support in to Axios. Note that this approach still requires the withCredentials flag.


You are getting the two thinks mixed.

You have "react-cookie" and "axios"

react-cookie => is for handling the cookie on the client side

axios => is for sending ajax requests to the server

With that info, if you want the cookies from the client side to be communicated in the backend side as well, you will need to connect them together.

Note from "react-cookie" Readme:

Isomorphic cookies!

To be able to access user cookies while doing server-rendering, you can use plugToRequest or setRawCookie.

link to readme

If this is what you need, great.

If not, please comment so I could elaborate more.


How do I make Axios send cookies in requests automatically?

set axios.defaults.withCredentials = true;

or for some specific request you can use axios.get(url,{withCredentials:true})

this will give CORS error if your 'Access-Control-Allow-Origin' is set to wildcard(*). Therefore make sure to specify the url of origin of your request

for ex: if your front-end which makes the request runs on localhost:3000 , then set the response header as

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

also set

res.setHeader('Access-Control-Allow-Credentials',true);

for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264

TLDR; one needs to set {withCredentials: true} in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.

참고URL : https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically

반응형