admin管理员组

文章数量:1317915

import Cookies from 'js-cookie';
//this returns null 
const authTokenFromCookies = Cookies.get('authToken');
console.log("AuthToken from cookies:", authTokenFromCookies);


// This returns the token set from the backend
const authToken = response.headers['authToken'];
console.log("AuthToken after login:", authToken);

js-cookie returns null but headers return the set cookies, Why?
What could be the cause?

import Cookies from 'js-cookie';
//this returns null 
const authTokenFromCookies = Cookies.get('authToken');
console.log("AuthToken from cookies:", authTokenFromCookies);


// This returns the token set from the backend
const authToken = response.headers['authToken'];
console.log("AuthToken after login:", authToken);

js-cookie returns null but headers return the set cookies, Why?
What could be the cause?

Share Improve this question asked Jan 14 at 12:28 StackTacticStackTactic 11 silver badge New contributor StackTactic is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 1

js-cookie returns null but headers return the set cookies, Why?

Because a cookie named authToken, and a response header named authToken, are absolutely not the same thing.

A cookie would be set via a Set-Cookie header. (A response header Set-Cookie: authToken=value would create a cookie named authToken.)

You did not log any actual cookie there in that second block, you logged the value of the header named authToken.

Hope this answers your query.

It should be noted that js-cookie can only interact with cookies which are accessible by javascript.

As @c3roe rightly mentioned, you are receiving null because there is no javascript-accessible cookie with the name authToken.

Debug Approach:

  • Check if there is a cookie with name authToken via devTools.
  • If the cookie is available is it a httpOnly cookie ( httpOnly cookies are inaccessible by javascript ).

本文标签: javascriptjscookie returns null but headers return the set cookieswhyStack Overflow