发送到客户端后不能设置报头



什么是错误在我的代码?我曾尝试使用jsonwebtoken生成令牌,但最终出现了一个错误"在它们被发送到客户端后无法设置标头"。这是详细的错误日志:

throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:393:5)
at ServerResponse.setHeader (node:_http_outgoing:644:11)
at ServerResponse.header (D:web devprojectsMern-Projectservernode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (D:web devprojectsMern-Projectservernode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (D:web devprojectsMern-Projectservernode_modulesexpresslibresponse.js:278:15)
at D:web devprojectsMern-Projectserverrouterauth.js:45:34
at D:web devprojectsMern-Projectservernode_modulesmongooselibmodel.js:5228:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11)
Emitted 'error' event on Function instance at:
at D:web devprojectsMern-Projectservernode_modulesmongooselibmodel.js:5230:15
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
code: 'ERR_HTTP_HEADERS_SENT'
}

我试图在使用jsonwebtoken包注册和登录网站时为用户生成令牌。下面是创建登录和登录方法的验证文件代码

const express = require("express");
const { default: mongoose } = require("mongoose");
const router = express.Router();
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("../db/conn");
const User = require("../model/userSchema");
router.get("/", (req, res)=>{
res.send("Hello world to server router js");
});
router.post("/register", (req, res)=>{
bcrypt.hash(req.body.password, 12, function (err, hash) { 
const newUser = new User({
name:req.body.name,
email: req.body.email,
phone: req.body.phone,
work: req.body.work,
password: hash

});
// Create token
const email = req.body.email;
const token = jwt.sign(
{ user_id: newUser._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "2h",
}
);
// save user token
newUser.token = token;
res.status(201).json(newUser);
if(!newUser.name || !newUser.email || !newUser.phone || ! newUser.work || !newUser.password){
return res.status(422).json({error: "Plz fill the required field"});
}
User.findOne({email: newUser.email}, function (err, userExist) { 
if(err){
console.log(err);
res.status(500).json({error: "failed to register"});
}else{
if(userExist){
return res.status(422).json({error: "Email already Exist"});
}else{
newUser.save();
res.status(201).json({message: "user registered succesfully"});
}
}
});
});
});
//LOgin route
router.post("/signin", (req, res)=>{
if(!req.body.email || !req.body.password){
return res.status(400).json({error: "Plz fill the required data"});
}else{
bcrypt.hash(req.body.password, 12, function (err, hash) { 
User.findOne({email: req.body.email}, function (err, foundUser) {
if(err){
console.log(err);
}else{
if(foundUser){
bcrypt.compare(req.body.password, foundUser.password, function (err, result) {
if(result){
res.json({message: "successfully log in"})
}else{
res.json({message: "incorrect password"});
}
});
const email = req.body.email;
const token = jwt.sign(
{ user_id: foundUser._id, email },
process.env.TOKEN_KEY,
{
expiresIn: "2h",
}
);
foundUser.token = token;
res.status(200).json(foundUser);
}else{
res.status(400).json({message: "user not found"});
};
}
})
})
}
});
module.exports = router;

数据库模式和模型的代码:

const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name:{
type:String,
required:true
},
email:{
type:String,
required:true
},
phone:{
type:Number,
required:true
},
work:{
type:String,
required:true
},
password:{
type:String,
required:true
},
tokens:[
{ token:{
type:String,
required:true
}
}]
});
const User = mongoose.model("User", userSchema);
module.exports = User;

请注意,无论何时发送响应,这并不意味着执行结束,而且HTTP对每个请求只有一个响应。因此,要停止函数的执行,您总是需要将return.

你的代码中有一些地方会产生问题:

newUser.token = token;
res.status(201).json(newUser);

您必须决定是发送客户端还是继续检查数据库。

因为在几行之后,您有这个条件,这可能会向客户端发送另一个响应:

if(!newUser.name || !newUser.email || !newUser.phone || ! newUser.work || !newUser.password){
return res.status(422).json({error: "Plz fill the required field"});
}

同样的问题发生在你的signin路由:

bcrypt.compare(req.body.password, foundUser.password, function (err, result) {
if(result){
res.json({message: "successfully log in"})
}else{
res.json({message: "incorrect password"});
}
});
...
res.status(200).json(foundUser);

相关内容

  • 没有找到相关文章

最新更新