0
votes

I am not getting cookies in my header. I am getting error at line#30. The Error is Cannot set headers after they are sent to the client UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch() I am using Postman to see the response. How to get cookies and then logout !!

user.js

1.  const express=require('express')
2.  const router=express.Router()
3.  const User=require('../models/User')
4.  const bcrypt=require('bcryptjs')
5.  const jwt=require('jsonwebtoken')

6.  router.post('/register',async(req,res)=>{

a.  //CHECKING IF EMAIL EXISTS
7.  const email_exists=await User.findOne({email:req.body.email})
8.  // console.log('email_exists',email_exists)
9.  if(email_exists) return res.status(400).send('Email already exists')

10. //HASHING PASSWORD
11. 
12. const salt=await bcrypt.genSalt(10)
13. const hashPassword=await bcrypt.hash(req.body.password,salt)

14. //Create a new User
15. const user=new User({
a.  name:req.body.name,
b.  email:req.body.email,
c.  password:hashPassword
16. });

17. try{
18. const savedUser=await user.save()
19. //sending only user id
20. res.json({user:user._id})
21. }catch(error){
a.  res.status(400).send(error)
22. }

23. });

24. router.post('/login',async(req,res)=>{
a.  //CHECKING IF EMAIL EXISTS
b.  const user=await User.findOne({email:req.body.email})
c.  if(!user) return res.status(400).send('Email or pass not exists')

d.  //CHECKING PASSWORD IS CORRECT
e.  const validPass=await bcrypt.compare(req.body.password,user.password)
f.  if(!validPass) return res.status(400).send('Invalid Password!')

g.  //creating and assigning a token
h
25. const token=jwt.sign({_id:user._id},process.env.ACCESS_TOKEN_SECRET,{expiresIn:'15m'})
26. 
27. 

28. // res.cookie() does is set the HTTP Set-Cookie header with the options provided. 
29. res.header('Authorization',token).send({token:token,refresh_Token:refreshToken}) 
30. res.cookie('access_token',token,{maxAge:3600,httpOnly:true})

31. 

32. })
33. 

34. module.exports=router;
 

server.js

const express = require("express");
const app = express();
require("dotenv/config");
const PORT = process.env.PORT || 4000;
const mongoose = require("mongoose");
const cookieParser=require('cookie-parser')

mongoose.connect(
  process.env.DB_URL,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => console.log("connected to DB")
);

app.use(cookieParser());
app.use(express.json());


app.use("/api/user", require("./routes/user"));
app.use("/api/posts", require("./routes/posts"));

app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));

1

1 Answers

1
votes

Problem is that you are sending response on line 29 before setting cookie.

try like this

29. res.cookie('access_token',token,{maxAge:3600,httpOnly:true})
30.res.header('Authorization',token).send({token:token,refresh_Token:refreshToken})