我该如何修复(节点:5796)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:错误?
Posted
技术标签:
【中文标题】我该如何修复(节点:5796)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:错误?【英文标题】:How can i fix (node:5796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: error? 【发布时间】:2021-06-02 18:17:23 【问题描述】:我运行了我的 node js 应用程序,但在注册我的应用程序后,它给了我这个错误。它是什么,我该如何解决。
(node:5796) UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT]: 在 ServerResponse.header (C:\Users\Children\ Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:767:10) 在 ServerResponse.send (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js: 170:12) 在 ServerResponse.json (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:267:15) 在 C:\Users\Children\Desktop\Web Projects\ Sermon_Tracker\app.js:171:9 在 processTicksAndRejec化(内部/进程/task_queues.js:97:5)(节点:5796)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict
(请参阅 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。 (拒绝 id:1)(节点:5796)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。
我想我知道错误在哪里查看错误,但我似乎无法修复它。这是我的代码:
app.post('/signup', async (req, res) =>
// res.json( status: "ok" );
// const firstName = req.body.firstName;
// const lastName = req.body.lastName;
//const username = req.body.email;
//const password = req.body.password;
// user = email;
// const User1 = mongoose.model("User", userSchema);
// const user2 = new User1(
// first_name: firstName,
// last_name: lastName,
// email: email,
// password: password,
// );
// user2.save();
// console.log(user + "Done");
// res.redirect("/workspace");
// Hashing passwords
const username, password: plainTextPassword = req.body;
userN = username;
if (!username || typeof username !== 'string')
return res.json( status: 'error', error: 'Invalid username' );
if (!plainTextPassword || typeof plainTextPassword !== 'string')
return res.json( status: 'error', error: 'Invalid password' );
if (plainTextPassword.length < 5)
return res.json( status: 'error', error: 'Password too small. Should be atleast 6 characters long.' );
const password = await bcrypt.hash(plainTextPassword, 10);
try
const response = await User.create(
_id: userN,
username,
password
);
console.log('user created successfully: ', response);
res.redirect('/workspace');
catch (error)
if (error.code == 11000)
return res.json( status: 'error', error: 'Username already taken' );
throw error
const item1 = new Item(
_id: userN,
date: "Date",
loc: "Location",
title: "Title",
passage: "Passage",
file: "File"
);
defaultItems.push(item1);
res.json( status: 'ok' );
);
下面是剩下的代码:
var userN;
var defaultItems = [];
mongoose.connect('mongodb://localhost:27017/sermontracker',
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
);
const ItemSchema = new mongoose.Schema(
_id: String,
date: String,
loc: String,
title: String,
passage: String,
file: String
);
const Item = mongoose.model("Item", ItemSchema);
app.post("/login", async (req, res) =>
const username, password = req.body;
const user = await User.findOne( username ).lean();
userN = username;
if (!user)
return res.json( status: 'error', error: 'Invalid username/password' )
if (await bcrypt.compare(password, user.password))
const token = jwt.sign( id: user._id, username: user.username , JWT_SECRET);
res.redirect('/workspace');
res.json( status: 'ok', data: token );
res.json( status: 'ok', error: 'Invalid user/password' );
);
app.post('/signup', async (req, res) =>
const username, password: plainTextPassword = req.body;
userN = username;
if (!username || typeof username !== 'string')
return res.json( status: 'error', error: 'Invalid username' );
if (!plainTextPassword || typeof plainTextPassword !== 'string')
return res.json( status: 'error', error: 'Invalid password' );
if (plainTextPassword.length < 5)
return res.json( status: 'error', error: 'Password too small. Should be atleast 6 characters long.' );
const password = await bcrypt.hash(plainTextPassword, 10);
try
const response = await User.create(
_id: userN,
username,
password
);
console.log('user created succecfully: ', response);
res.redirect('/workspace');
catch (error)
if (error.code == 11000)
return res.json( status: 'error', error: 'Username already taken' );
throw error
res.json( status: 'ok' );
const item1 = new Item(
_id: userN,
date: "Date",
loc: "Location",
title: "Title",
passage: "Passage",
file: "File"
);
defaultItems.push(item1);
);
app.get("/", function (req, res)
res.render("home");
);
app.get("/change-password", function (req, res)
res.render("changepass");
);
app.get("/signup", function (req, res)
res.render("signup");
);
app.get("/login", function (req, res)
res.render("login");
);
app.get("/workspace", function (req, res)
Item.find( _id: userN , function (err, foundItems)
if (foundItems.length == 0)
Item.insertMany(defaultItems, function (err)
if (err)
console.log(err);
else
console.log("Added items");
);
res.redirect("/workspace");
else
res.render("workspace", itemList: foundItems );
);
);
app.post("/workspace", function (req, res)
const date = req.body.input1;
const location = req.body.input2;
const title = req.body.input3;
const passage = req.body.input4;
const file = req.body.input5;
const item = new Item(
_id: userN,
date: date,
loc: location,
title: title,
passage: passage,
file: file
);
item.save();
res.redirect("/workspace");
);
【问题讨论】:
【参考方案1】:首先,userN
似乎不是一个变量。 (但没有抛出错误,所以..)
您正在重定向,然后返回一些 JSON。这就是引发错误的原因。在重定向之前尝试返回 JSON。 (如果你需要)。该错误解释了这一点(以某种神秘的方式:))
【讨论】:
你想让我展示整个代码吗?我已经将userN
定义为函数外部的全局变量。我将对其进行编辑并在其中添加大部分代码。
@LublubXT 试试我在回答中所做的事情。它应该可以工作。我不再需要任何代码 :)
好的,我编辑了它,除了导入模块和运行服务器之外,我还添加了其余代码。
好的,我会试试的。
所以你想让我删除 throw 部分以及 res.json( status: 'ok' );
?以上是关于我该如何修复(节点:5796)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:错误?的主要内容,如果未能解决你的问题,请参考以下文章
我该如何修复(节点:14352)UnhandledPromiseRejectionWarning:MongoError:E11000 重复键错误集合:错误?