Accessing Set-Cookie value from response.headers in axios

Viewed 7541

I am using VueJS and Axios to send a request like this:

 axiosAPI.get('/login/flows', {params: {id: 'string'}})
            .then(res => {
                console.log('cookie', res.headers)
             }

In return server sends me this response:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Type
Cache-Control: private, no-cache, no-store, must-revalidate
Content-Length: 646
Content-Type: application/json; charset=utf-8
Date: Thu,xxxx 13:56:21 GMT
Set-Cookie: csrf_token=Lxv3zynm1Fua0hU0/W1+R2w=; Path=/.ory/kratos/public/; Domain=x.y ; Max-Age=31536000; HttpOnly; SameSite=Lax
Vary: Origin
Vary: Cookie

As you can see, server sends a csrf-token in Set-Cookies. but when I try to print out the headers I can not get and store the csrf-token. In addition, browser doesn't store the token at all in the storage section.

I need to use the csrf-token inside of this cookie but I don't know how I can do this?

Note: i don't have any access to back-end codes.

2 Answers

Maybe you can use the axios-cookiejar-support.

https://www.npmjs.com/package/axios-cookiejar-support

A medium article showing how to use it.

https://medium.com/@adityasrivast/handling-cookies-with-axios-872790241a9b

Sample (getting cookie from a login page):

const axios = require('axios');
const wrapper = require('axios-cookiejar-support').wrapper;
const CookieJar = require('tough-cookie').CookieJar;

const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));

const url = '<your url>';

const params = new URLSearchParams();
params.append('username', '<username>');
params.append('password', '<password>');
client.post(`${url}/Login`, params, {
  headers: {
    'Accept': '*/*'
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

Using this will get you the whole string for that header:

const cookieHeaders = res.headers['Set-Cookie'];

After that, you could split the string in an array with

cookieHeaders.split('; ');

In the array, you can then get the specific one you need.

Related