[英]ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client at Server Response
I am trying to create a simple REST API with NodeJS and Express with the mongo database.我正在尝试使用 NodeJS 和 Express 使用 mongo 数据库创建一个简单的 REST API。 I have stored all of my data in JSON files.我已将所有数据存储在 JSON 文件中。 The data is in the form of an array of objects.数据采用对象数组的形式。
I have paths like我有类似的路径
fund-name/:portId`try {
const { email, password } = req.body;
const user = await Users.findOne({ email });
if (!user)
return res.status(400).json({ msg: "This email is not exists." });
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
const token = jwt.sign({ _id: user._id, role: user.role }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
const { _id, firstName, lastName, email, role, fullName } = user;
res.status(200).json({
token,
user: {
_id,
firstName,
lastName,
email,
role,
fullName,
},
});
} else {
return res.status(400).json({ msg: "Password is incorrect." });
}
// console.log(user);
res.json({ msg: "Login Successfully." });
} catch (error) {
return res.status(500).json({ msg: error.message });
} let token = req.headers.authorization;
const user = jwt.verify(token, process.env.JWT_SECRET);
req.user = user;
console.log(req.user);`
I've solved this problem with:我已经解决了这个问题:
let token = req.headers.authorization;
token = token.replace('Bearer ', '');
const user = jwt.verify(token, process.env.JWT_SECRET);
req.user = user;
console.log(req.user);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.