node.js - 使用 NODEJS 保存到 Mongodb 后如何获得响应

标签 node.js mongodb express

通过保存来自 postman 的数据,我想从 MongoDB 获得响应,包括新创建的文档

代码

async save(req, res){

        const {score, multiplier, level} = req.body;
        const scores =  new Result({score, multiplier, level});
        const savedRes = await scores.save().then(resp=>{
            return resp
                .sendStatus(200)
                .send({
                message:'new record is saved',
                data: savedRes
 
            })
        }).catch(error=>res.sendStatus(500).send(error))
    }

mongo配置

const app = express()
 mongoose.connect(process.env.MONGODB_URL,{
    useNewUrlParser: true,
    useUnifiedTopology: true,
 })
 const con= mongoose.connection
try{
    con.on('open',() => console.log('db connected'))
} catch(error){
     console.log(error)
}
 app.use(cors({origin:"*"}))

实际结果

  • 在 MongoDB Atlas 中创建文档,postman 响应正文中出现内部服务器错误以及(node:96318) UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:无法设置在 vscode 终端中发送到客户端后的 header

预期结果

{
message: 'new record is saved',
data: {
    level: 1,
    multiplier:8
}
}

最佳答案

来自documentation , res.sendStatus(..)是:

Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

所以它已经发送了响应,您尝试稍后通过 res.send(..) 发送响应。您应该仅通过res.status(<statusCode>)设置状态。但由于默认状态代码是 200 ,你可以简单地这样做:

const {score, multiplier, level} = req.body;
const scores =  new Result({score, multiplier, level});
const savedRes = await scores.save();
res.send({ message:'new record is saved', data: savedRes });
          

关于node.js - 使用 NODEJS 保存到 Mongodb 后如何获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69265507/

相关文章:

node.js - Sequelize 原始查询不会从 Postgres 数据库返回确切的结果

node.js - 比较编辑器不在 node.js 项目上的 eclipse 上工作

使用 rmongodb 在 R 中运行高级 MongoDB 查询

mongodb - 推送到 MongooseJS 子文档而不创建重复项

javascript - 如何从 mongoDB 中分离字符串

node.js - express.js 中的路由器优先顺序

node.js - 快速验证器 : How parameters passed to validator functions

node.js - NX : Copy one extra file to build directory

javascript - JS 全局变量在 setTimeout 中未定义

mongodb:启用文本搜索