Monday 31 August 2020

Not setting cookie correctly JWT Express React

This is my first attempt at authentication. When I test in postman I see a cookie in the cookie tab. When I am on the network tab in the browser I can see in the response headers Set-Cookie. When I copy the cookie and test the protected routes I am good to go. When I check the application tab I do not see a cookie being set and when I console.log the response on my front end, I do not see the cookie or token anywhere. document.cookie is an empty string. What am I missing here?const express = require('express'); const app = express(); const mongoose = require('mongoose'); const dotenv = require('dotenv'); const cors = require('cors'); const cookieParser = require('cookie-parser') // Import Routes const authRoute = require('./routes/auth'); const postRoute = require('./routes/posts'); dotenv.config(); const port = process.env.PORT; // Connect to DB mongoose.connect( process.env.DB_CONNECT, { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => console.log('connected to db')); //Middleware app.use(cors({credentials: true,})); app.use(express.json()); app.use(cookieParser()); app.use('/api/posts', postRoute) app.use('/api/user', authRoute) app.listen(port, () => console.log(`Listening on port ${port}....`)) router.post('/login', async (req,res) => { //Validate data from user const {error} = validation.login(req.body) if (error) { return res.status(400).send(error.details[0].message) }//Check if user is already in DB const user = await User.findOne({email: req.body.email}); if (!user) { return res.status(400).send('Email or password is incorrect'); }//Check password const validPass = await bcrypt.compare(req.body.password, user.password); if (!validPass) { return res.status(400).send('Email or password is incorrect'); }//Create and assign a token const token = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET) res.cookie("token", token) res.status(200).send('User is logged in') })

Submitted August 31, 2020 at 07:00PM by eurodollars

No comments:

Post a Comment