Cookie works when I use Postman, but does not show in browser

Viewed 1352

I am working on a Nodejs Project and pug template. When I login on postman, Cookie is sent, but when I use Chrome or any other browser, It does not show cookie

const signToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  })
}

const createSendToken = (user, statusCode, req, res) => {
  const token = signToken(user._id)

  res.cookie('jwt', token, {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
    ),
    httpOnly: true,
  })


  res.status(statusCode).json({
    status: 'success',
    token,
    data: {
      user,
    },
  })
}

I also am using cookie-parser and cors from npm

app.use(
  cors({
    credentials: true,
  })
)

I have tried using cors without any option. Still doesnt work.

When I log req.cookies to the console, I get

[Object: null prototype] {}

But using postman, I get the jwt token displayed in the console.

Here is my login route. How do I include the credentials

export const login = async (email, password) => {
  try {
    const res = await axios({
      method: 'POST',
      url: 'http://127.0.0.1:3000/api/v1/users/login',
      data: { email, password },
    })

    if (res.data.status === 'success') {
      showAlert('success', 'Logged in successfully!')
      window.setTimeout(() => {
        location.assign('/')
      }, 1500)
    }
    console.log(res)
  } catch (err) {
    showAlert('error', err.response.data.message)
  }
}
2 Answers

httpOnly cookies are set by the server and arent accessible by the browser, only the server. When making your request try adding withCredentials: true in an axios (or credentials: 'include' for fetch):

axios.post('/your-route', {your-body}, {withCredentials: true});
-- or --
fetch('/your-route', {credentials: 'include'}) 
//may need cross-origin or same-origin if CORS Origin is set

Check out the mozilla docs on using http cookies for further reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

I had to look for it, the whole day, I found that using http://localhost:3000 instead of http://127.0.0.1:3000 was all I needed for the solution, try this.....

Related