首页 > 解决方案 > 错误:发送后无法设置标头。在节点 js

问题描述

我是节点 js 的新手,当我尝试从 react 将数据发送到数据库时,在我的节点 js 上出现错误“发送后无法设置标题。我一直在寻找同样的问题,但这并不能帮助我解决这个问题

我试过在帖子上使用 writeHead(第二个),但没有帮助,是因为我发送了相同的图像吗?我只是在发送相同的图像时遇到问题

app.post('/list', function(req, res){
    const {namaCabor, descCabor, imgCabor } = req.body;
    connectDb.collection('listCabangOlahraga').insertOne(req.body, function(err, res){
        console.log(res.insertedCount +'data inserted');
    });
    res.send(req.body);
});

app.post('/add', function(req, res){
    const {categoryName, categoryDesc, categoryImage, namaCabor, descCabor, imgCabor } = req.body;
    connectDb.collection('listCategoryCabangOlahraga').insertOne(req.body, function(err, res){
        console.log(res.insertedCount +'data inserted'); 
        if(err) throw err;
    });
    res.writeHead(200, {'Content-Type' : 'application/json'});
    res.end(JSON.stringify(req.body));
});

标签: node.jsmongodb

解决方案


快速分析:您的代码涉及写入 MongoDB 集合。它有一个异步回调。我猜 res.write() / res.send() 应该包含在回调中?

如果没有,它们甚至在数据库操作完成之前就被执行,我们不知道它是否成功。

app.post('/list', function(req, res){
    const {namaCabor, descCabor, imgCabor } = req.body;
    connectDb.collection('listCabangOlahraga').insertOne(req.body, function(err, res){
        console.log(res.insertedCount +'data inserted');
        // <----- Handle the error here and print response accordingly.
    });
    res.send(req.body); //Move this inside callback. Return error response if err encountered.
});

app.post('/add', function(req, res){
    const {categoryName, categoryDesc, categoryImage, namaCabor, descCabor, imgCabor } = req.body;
    connectDb.collection('listCategoryCabangOlahraga').insertOne(req.body, function(err, res){
        console.log(res.insertedCount +'data inserted'); 
        if(err) throw err;
        // <----- Handle the error here and print response accordingly.
    });
    res.writeHead(200, {'Content-Type' : 'application/json'}); // Move this inside callback.
    res.end(JSON.stringify(req.body)); //Write response from the callback.
});

基本上出现错误是因为 res.write() / res.send() 在设置标题之前被调用

此外,在任一位置重命名 res 对象也是一个好主意(也许可以重命名 MongoDB 写回调中的(结果)对象以避免与快速路由的(响应)对象的res潜在混淆)res


推荐阅读