发送给客户端后无法设置 headers...未处理的承诺拒绝

Cannot set headers after they are sent to the client...Unhandled promise rejection

我的 header 中没有收到 cookie。我在第 30 行收到错误。 错误是 Cannot set headers after they are send to client UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下在异步函数内部抛出,或者拒绝未使用 .catch() 处理的承诺 我正在使用 Postman 查看响应。如何获取 cookie 然后注销 !!

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}`));

问题是您在设置 cookie 之前在第 29 行发送响应。

这样试试

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