我想编写一个小型应用程序,该应用程序通过POST接收欢迎消息并通过GET返回。如果我仅调用一种方法(GET或POST),就没有问题,但是一旦我调用GET和POST,就会收到以下消息:
events.js:174
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\node_modules\express\lib\response.js:170:12)
at Greeting.find (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\routes\hello.js:16:13)
at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\model.js:4568:16
at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\query.js:4315:12
at process.nextTick (C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\helpers\query\completeMany.js:35:39)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\model.js:4570:13
at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\query.js:4315:12
at process.nextTick (C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\helpers\query\completeMany.js:35:39)
at process._tickCallback (internal/process/next_tick.js:61:11)
这是我的代码:
const express = require("express");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const router = express.Router();
const Greeting = mongoose.model("Greeting", new Schema({message: String}));
router.get("/", (req, res) => {
Greeting.find({message: "Hello World!"}, (err, greetings) => {
if (err) {
console.log(err);
res.status(500).send(err);
return;
}
res.send(JSON.stringify(greetings));
});
res.send("There are no greetings!");
});
router.post('/', (req, res) => {
mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true});
new Greeting(req.body).save()
.then(() => {
res.send('success');
})
.catch(err => {
console.log(err);
res.status(500).send("Error: " + err)
});
});
module.exports = router;
我扫描了this question,但是找不到解决我问题的方法。
答案 0 :(得分:1)
Greeting.find
是一个异步函数,因此行res.send("There are no greetings!");
在Greeting.find
的回调运行之前运行,这意味着响应'There are no greetings!'
在回调运行之前已发送到客户端
然后在Greeting.find
回调中,您尝试再次向客户端发送响应,从而导致错误。