gpt4 book ai didi

javascript - 与 mongoDB(和 Mongoose )的 promise 链接。如果已发送响应,如何在 .then() 之后使用 .save() 并正确突破 promise 链?

转载 作者:行者123 更新时间:2023-11-29 20:27:25 26 4
gpt4 key购买 nike

我有以下用于注册用户的代码。我首先验证用户输入的地方。其次,我检查用户是否已经存在,如果存在,它应该返回响应 400。如果不存在,则转到第 3 步并添加新用户。最后在第 4 步中返回新创建的条目。从逻辑上讲,它可以正常工作并将数据正确地添加到数据库中,但是它总是在 postman (从第 2 步开始)上以 'User already exists' 响应,即使它是一个新用户已将用户正确添加到D b。这让我觉得第三步是在发送第 2 步中的响应之前完成的,这意味着我没有正确链接 promise 。此外,新用户永远不会作为响应发回,我认为这是因为我没有正确使用 Promise.then() 和 user.save() 。我还收到以下错误(在代码之后发布),我理解这意味着我在发送第一个响应后尝试发送第二个响应。我可以用 async 和 await 解决这个问题,但我想学习如何用这种方式来解决这个问题。谢谢,任何帮助表示赞赏。

const { User, validateUser } = require('../models/userModel');
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();

router.post('/', (req, res) => {
return Promise.resolve()
.then(() => {
//Step 1: validae the user input and if there is an error, send 400 res and error message
console.log('My user post body req::', req.body);
const { error } = validateUser(req.body); //this is using Joi.validate() which has a error property if errors are found
if (error) {
return res.status(400).send(error.details[0].message);
}
})
.then(() => {
//step 2: check if user already exists, if yes send res 400
let user = User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('User already exists');
}
})
.then(() => {
//Step 3: enter new user into the database
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
return user.save();
})
.then((result) => {
//step 4: return the newly added user
return res.status(200).send(result);
})
.catch((error) => {
console.log('Error Adding new User', error);
});
});

module.exports = router;

我从 catch 中收到以下错误消息。即使我是,我也会带着每一个回应回来

Error Adding new User Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:494:11)
at ServerResponse.header (/home/ssaquif/WebDevProjects/movie-reviews-backend/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ssaquif/WebDevProjects/movie-reviews-backend/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/ssaquif/WebDevProjects/movie-reviews-backend/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/ssaquif/WebDevProjects/movie-reviews-backend/node_modules/express/lib/response.js:158:21)
at /home/ssaquif/WebDevProjects/movie-reviews-backend/routes/users.js:35:27
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'ERR_HTTP_HEADERS_SENT'

最佳答案

您不需要在您的 route 使用 Promise.resolve。您只需要一个 then block 链,您需要在其中将一个值返回给下一个 block 。

我像这样重构了你的代码:

router.post("/", (req, res) => {
//Step 1: validate the user input and if there is an error, send 400 res and error message
console.log("My user post body req::", req.body);
const { error } = validateUser(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}

//step 2: check if user already exists, if yes send res 400
User.findOne({ email: req.body.email })
.then(user => {
if (user) {
return res.status(400).send("User already exists");
}
return;
})
.then(() => {
//Step 3: enter new user into the database
let user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
return user.save();
})
.then(result => {
//step 4: return the newly added user
return res.status(200).send(result);
})
.catch(error => {
console.log("Error Adding new User", error);
res.status(500).send("Error");
});
});

用户注册成功后会出现这样的结果:

{
"_id": "5dd65df52f7f615d8067150d",
"name": "ssaquif",
"email": "test@test.com",
"password": "123123",
"__v": 0
}

当使用现有的电子邮件时,响应将像这样,状态码为 400。

User already exists

关于javascript - 与 mongoDB(和 Mongoose )的 promise 链接。如果已发送响应,如何在 .then() 之后使用 .save() 并正确突破 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58970458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com