hash
hash

Reputation: 13

Send cookie with get request

I 'm authenticating with site https://a.com. Once I authenticate, I access http://b.com. a.com sets a cookie for the session that I need to send with when I make a get request from b.com to a.com.

Can you please tell me, how I can get the cookie and pass it on with my request.

I have tried sending the requests with "withCredentials": true, Also tried using the axios-cookiejar-support with tough-cookie. But doesn't seem to work.

axios
.get(a.com/path-requiring-cookie, {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'access-control-allow-credentials': true,
  },
})
.then(res => {
  console.log(res.data);
});

This is the code that I have to send the request.

But this doesn't seem to send the cookie with the request. Can someone please clarify.

Upvotes: 1

Views: 2260

Answers (2)

avcajaraville
avcajaraville

Reputation: 9084

Have a look to this question.

The problem you are trying to solve is to read/send cookies from/to different domains.

One solution, as stated in the previously linked question would be to set some headers on http://b.com

Access-Control-Allow-Origin: http://b.com
Access-Control-Allow-Credentials: true

You do that on the server that has the domain http://b.com

Something along those lines should solve the issue for you.

Upvotes: 1

Harsh Makadia
Harsh Makadia

Reputation: 3443

Why don't use a javascript function instead that helps use fetch the Cookie based on it's name like below

function GetCookie(cName) {
  const name = `${cName}=`;
  const decodedCookie = decodeURIComponent(document.cookie);
  const ca = decodedCookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
};

console.log(GetCookie("SID"))

Upvotes: 1

Related Questions