簡體   English   中英

錯誤[ERR_HTTP_HEADERS_SENT]:將標頭發送到Node JS中的客戶端后,無法設置標頭

[英]Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client in Node JS

我正在嘗試使用無法正常工作但出現上述錯誤的特定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);
        });
    });
});

這是我得到的錯誤...

錯誤

有人可以幫幫我嗎?

'/update/:id'路由中,您要發送一個res.end()然后在三行之后再次執行。 如果刪除第一個res.end() ,它將正常工作。

如果todo丟失,也應該return

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);
        });
    });
});

此錯誤通常表示您多次發送響應。

請注意,您發送了兩個響應,一個在另一個res.json()res.end()

如果出於某種原因想要結束響應,請使用res.end() ,否則請使用res.status(200).json({ result: 'Data updated' + todo })

如果兩者都發送,它將抱怨發送后(通過res.status().json() )嘗試修改響應(通過res.end() res.status().json()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM