【问题标题】:cannot set headers after they are sent to the client - mongoose将标头发送到客户端后无法设置标头 - mongoose
【发布时间】:2019-08-13 20:09:44
【问题描述】:

我想编写一个通过 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,但找不到我的问题的解决方案。

【问题讨论】:

  • .find() 回调中检查greetings 是否存在和length,例如,仅使用if/else 子句发送响应。 res.send 被调用了两次。

标签: node.js express mongoose


【解决方案1】:

然后在Greeting.find 回调中,您尝试再次向客户端发送响应,这会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2019-05-17
    • 2022-01-14
    • 2021-04-07
    相关资源
    最近更新 更多