gpt4 book ai didi

javascript - 错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client in Node JS

转载 作者:行者123 更新时间:2023-12-01 00:57:50 26 4
gpt4 key购买 nike

我正在尝试使用特定 ID 更新数据,该 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

有人可以帮我吗?

最佳答案

此错误通常意味着您多次发送响应。

请注意,您依次发送了两个响应 res.json()res.end()

如果您出于某种原因想要结束响应,请使用 res.end(),否则使用 res.status(200).json({ result: 'Data Updated' + 待办事项 })

如果您同时发送两者,它会在发送(通过 res.status().json()<)后尝试修改响应(通过 res.end())/)

关于javascript - 错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client in Node JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56384359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com