PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] Why browser can't set cookies by default

 October 13, 2022     axios, cookies, cross-domain, express, http-headers     No comments   

Issue

I know there are a lot of discussion about this topic already did. and i think i have followed all the instruction but still can't succeed.I think i'm missing something.

Here's my cookie :

 const cookieOptions = {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
    path: '/',
    sameSite: 'lax',
    maxAge: 1000 * 60 * 60 * 1,
  };
  if (process.env.NODE_ENV === 'production') {
    cookieOptions.secure = true;
  }

  res.cookie('jwt', token, cookieOptions);

Cors :

app.use(
  cors({
    origin: ['http://localhost:3000'],
    credentials: true,
  })
);

Frontend :

const { data } = await axios.post(
        "http://127.0.0.1:8000/api/v1/users/login",
        {
          email: enteredEmail,
          password: enteredPassword,
        },
        { withCredentials: true }
      );

I have also used axios.defaults.withCredentials = true; . But still i can't find my jwt in Application > cookies.

Here's my Response header enter image description here

and this is my request header

enter image description here


Solution

"res.cookie()" only set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.If you take a look closely at the response header, see that jwt=... is present in the Set-Cookie header.

For your implementation, where you try to access the data from the axios response, you should look into res.json() or res.send(), as it directly sends the response back in the body, not the header.



Answered By - MTN
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing