0

I want to write a small app that receives a welcome message via POST and returns it via GET. If I call only one method (GET or POST), there are no problems, but as soon as I call GET and POST, I get the following message:

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)

This is my code:

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;

I scanned this question but could not find a solution for my problem.

Andreas
  • 430
  • 5
  • 21
  • 1
    In `.find()` callback check for `greetings` exists and `length` for example and send response there only with `if/else` clause. `res.send` is getting called twice. – ambianBeing Aug 13 '19 at 12:00

1 Answers1

1

Greeting.find is an async function so the line res.send("There are no greetings!"); runs before the callback of Greeting.find runs which means the response 'There are no greetings!' is sent to the client before the callback ever runs.

Then in Greeting.find callback you're trying to send a response to the client again which causes the error.

Yousuf Khan
  • 334
  • 3
  • 12