错误[ERR_HTTP_HEADERS_SENT]:将标头发送到Node JS中的客户端后,无法设置标头

时间:2019-05-30 19:16:29

标签: javascript node.js mongodb express mongoose

我正在尝试使用无法正常工作但出现上述错误的特定ID更新数据。

更新后,首先我在数据库中搜索该特定ID,然后将数据保存到MongoDB

这是我的server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//importing MongoDB model schema
let ToDo = require('./todo.model');

const app = express();
const todoRoutes = express.Router();

const PORT = 4000;

//middlewares
app.use(bodyParser.json());
app.use(cors());
app.use('/todos', todoRoutes);

//connection to the MongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/todos', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () =>{
    console.log("Connected to the MongoDB through port: 27017");
 });

app.listen(PORT, () => { 
    console.log(`Listening to port: ${PORT}`);
});

//get all data - removed to show only the code snippet I am getting errors

//get data by an ID - removed to show only the code snippet I am getting errors

//add items to database -removed to show only the code snippet I am getting errors

//update items
todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;
        res.end();

        todo.save().then(todo => {
            res.json(200).send("Data Updated! " + todo);
            res.end();
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});

这是我得到的错误...

Error

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

'/update/:id'路由中,您要发送res.end(),然后在3行后再次发送。如果您删除第一个res.end(),它应该可以工作。

如果缺少return,您也应该todo

todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) return res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;

        todo.save().then(todo => {
            res.status(200).send("Data Updated! " + todo);
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});

答案 1 :(得分:1)

此错误通常表示您多次发送响应。

请注意,您依次发送两个回复res.json()res.end()

如果您出于某种原因想要结束响应,请使用res.end(),否则请使用res.status(200).json({ result: ‘Data updated’ + todo })

如果您同时发送这两个消息,它将在发送(通过res.end())后抱怨尝试修改响应(通过res.status().json()