【问题标题】:Cannot set headers after they are sent to the client in node js将标头发送到节点js中的客户端后无法设置标头
【发布时间】:2018-05-15 06:47:41
【问题描述】:

我只有在调用 get 方法时才会收到此错误(不是每次)。

这是我的节点函数,它返回一个响应。

exports.GetDepartmentList = function (req, res) {
    fs.readFile('./api/tempFiles/department.json', 'utf8', function (err,response) {
        res.status(200).send({
            success: true,
            data: JSON.parse(response)
        });
        return res.json();
        dbConn.close();
    }).catch(function (err) {
        res.status(500).send({
            success: false,
            message: err.message
        });
        return res.json();
        dbConn.close();
    });
};

我已经检查了 StackOverflow 的所有问题,但没有一个对解决我的问题有帮助。

【问题讨论】:

  • 为什么写return res.json();?还有dbConn.close(); 在它之后,因为return 终止了函数dbConn.close(); 永远不会被调用。使用ressendjson 方法,不要同时使用
  • 我删除了它,但它不起作用。发生同样的错误。@Dhyey
  • 请用更新的代码编辑问题

标签: node.js angular get


【解决方案1】:

当您向客户端发送多个响应时发生此错误。

我认为你应该尝试这样的事情(没有 catch)

exports.GetDepartmentList = function (req, res) {
    fs.readFile('./api/tempFiles/department.json', 'utf8', function (err, response) {
        if (err) {
            res.status(500).json({
                success: false,
                message: err.message
            });
        }
        else {
            res.status(200).json({
                success: true,
                data: JSON.parse(response)
            });
        }
        dbConn.close(); // Really usefull ?
    });
};

希望对你有帮助。

【讨论】:

  • 谢谢!但是你能解释一下为什么我不应该使用 catch 吗??
  • 也许你可以使用catch,但我认为你不需要,因为你的回调函数(err,response)已经捕获了一个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2022-01-14
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多