通过保存来自 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/