![](/img/trans.png)
[英]Mongoose : Cannot set headers after they are sent to the client
[英]cannot set headers after they are sent to the client - mongoose
我想編寫一個小應用程序,該應用程序通過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;
我掃描了這個問題,但是找不到解決我問題的方法。
Greeting.find
是一個異步函數,因此,行res.send("There are no greetings!");
在Greeting.find
的回調運行之前運行,這意味着響應'There are no greetings!'
在回調運行之前被發送到客戶端。
然后,在Greeting.find
回調中,您嘗試再次將響應發送給客戶端,從而導致錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.