Home > Mobile >  JWT: Cookies not being set when server (localhost:3001/login) is not accessed directly (MERN)
JWT: Cookies not being set when server (localhost:3001/login) is not accessed directly (MERN)

Time:12-15

So I am trying to create a token for authentication.

Scenario 1: When I am accessing my local server directly localhost:3001/login I was able to update/set cookies. Here's a snippet of my code:

app.get('/login', async (req, res) => {
  const run_query = (username, password) => {
    UserModel.findOne({ username:username }, (e, obj) => {
      if(obj === null)
        res.send('no user')

      else if(e)
        res.send(obj)

      else {
        bcrypt.compare(password, obj.password, function(e, resp) {
          if(resp) {
            const accessToken = createTokens(obj)

            res.cookie(`access-token`, accessToken);
            res.send(obj)
          }
          else
            res.send('wrong password')
        })
      }
    })
  }
  run_query(req.body.username, req.body.password)
})

Scenario 2: When I am trying to access localhost:3001/login via axios.get on button click (React) I am able to run my query successfully and send the obj data of the user but it is not setting the cookie.

Here's how I access /login via React:

  const login = async () => {
    try {

      const res = await axios.get('http://localhost:3001/login', {
        username: username,
        password: password
      })

      const loginTrue = (res) => {
        setLogged(true)
        console.log(res)
      }

      res.data === 'wrong password' ? alert('Wrong Password')
        : res.data === 'no user' ? alert('Username not Found')
        : res.data === 'empty' ? alert('Please Fill up all fields')
        : res.data._id !== undefined && res.data._id !== '' ? loginTrue(res.data)
        : alert('Error: '   res.data.Error)

    } catch (e) {
      console.log(e)
    }
  }

Question:

  • Why am I only able to update my cookie when accessing localhost:3001/login directly?

I must've missed something or did something wrong. Thanks!

CodePudding user response:

There has been this thread regarding how cookies themselves work and how Axios is handling them. There are a couple of things that might work depending on your environment so I won't make it a duplicate.

  • Related