chichi
chichi

Reputation: 3301

How to send cookies in express?

router.post('/login', async (req, res) => {
  const logInEnvironment = browser(req.headers['user-agent']);
  const ipAddress = requestIp.getClientIp(req);
  const userEmail = req.body.userEmail.toLowerCase();
  const password = req.body.password;

  // Form validation
  const validation = await validateLoginInput(req.body);

  // Check validation
  if (!validation.isValid) {
    return res.status(400).json(validation.errors);
  }

  // Find user by email
  const auth = await Auth.findOne({ userEmail }, { userLoginInfo: 0 });

  //Check if user exists
  if (auth === null) {
    console.log('aaaa');
    res.cookie('send2', 'shhhhhent!');
    res.status(200);
    return res
      .status(400)
      .json({ authFailedMessage: 'Email or password is incorrect' });
  } else if (auth !== null) {
    bcrypt.compare(password, auth.password).then((isMatch) => {
      if (isMatch) {
        return res.cookie('failed', 'yess!').status(200).json({succeeded: 'hiii'})
      } else if (!isMatch) {
        return res.cookie('succeeedd', 'noooo!').status(400).json({failed: 'hiii'})
      }
    });
  }
});

I have this code. But, the res.json has been returned without cookies. enter image description here enter image description here

Moreover, I added these commands in my index.js file

const cookieParser = require('cookie-parser');
app.use(cookieParser());

I also tested if res.cookie() was working in another route

router.get('/cookie', (req, res) => {
   res.cookie('hellooo', 'hiiiiii')
   res.send('woooorked?')
})

This was returning cookie and I can see that in the dev-panel on Chrome. What have I done wrong in the first code that cookies are not sent to the browser?

Upvotes: 0

Views: 516

Answers (1)

Xuan Tin
Xuan Tin

Reputation: 51

Did you try to split the code like

router.get('/cookie', (req, res) => {
   res.cookie('hellooo', 'hiiiiii')
   res.send('woooorked?')
})

Can you test with this code

router.post('/login', async (req, res) => {
  const logInEnvironment = browser(req.headers['user-agent']);
  const ipAddress = requestIp.getClientIp(req);
  const userEmail = req.body.userEmail.toLowerCase();
  const password = req.body.password;

  // Form validation
  const validation = await validateLoginInput(req.body);

  // Check validation
  if (!validation.isValid) {
    return res.status(400).json(validation.errors);
  }

  // Find user by email
  const auth = await Auth.findOne({ userEmail }, { userLoginInfo: 0 });

  
  res.cookie('send2', 'shhhhhent!');
  return res.json({ authFailedMessage: 'Email or password is incorrect' });
});

Then you check the header of the request and find the header name set-cookie, if it visible, you have got it enter image description here

Upvotes: 1

Related Questions