发送后设置错误 Headers - Node.js

Error Setting Headers After They are Sent - Node.js

我正在使用 nodejs 构建一个 api 以与客户端 (android) 和管理员 (web) 进行交互。

当 api 启动时,它对管理员来说工作正常并且视图正确呈现但是当我将客户端连接到 api 时,我得到一个 error/warning服务器控制台如:

App at port 4003
db connection opened successfully
Categroies Count:       2
Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header 
    (E:\nodeCMSApp\node_modules\express\lib\response.js:767:10)
    at ServerResponse.json 
    (E:\nodeCMSApp\node_modules\express\lib\response.js:264:10)
    at Categories.find.select.exec.then.data 
    (E:\nodeCMSApp\routes\admin_categories.js:20:22)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    (node:13880) UnhandledPromiseRejectionWarning: Unhandled promise 
    rejection (rejection id: 1): Error: Can't set headers after they are 
    sent.
    (node:13880) [DEP0018] DeprecationWarning: Unhandled promise rejections 
    are deprecated. In the future, promise rejections that are not handled 
    will terminate the Node.js process with
    a non-zero exit code.

这是我的 api 代码片段:

router.get('/', (req, res) => {

Categories.find({})
    .select('title slug image _id')
    .exec()
    .then(data => {
        if (data) {
            res.status(200)
                .json({
                    success: true,
                    count: data.length,
                    categories: data
                })
            // I understand that the problem lies here
            res.render('admin/all_categories', {
                categories: data
            });

        } else {
            res.render('all_categories', {
                categories: null
            });
        }
    })
    .catch(error => {
        console.error(error);
        res.send('Error 404');
    });

});

我明白这是因为我已经用响应 object 渲染了一个视图,我再次调用它 return 一些 json 给客户。

我的问题是如何同时为客户端呈现视图和 return json 数据而不会出现任何错误? 谢谢

在您的代码中,如果一切顺利,您将向用户发送两个响应:

  if (data) {
    res.status(200).json({
      success: true,
      count: data.length,
      categories: data
    });

    // I understand that the problem lies here
    res.render('admin/all_categories', {
      categories: data
     });  
  }

在您调用 res.json、res.send、res.redirect、res.render 等时,您正在将正确的 headers 发送到用户(浏览器)所以,在你的情况下,在 res.status(200).json 你试图发送 res.render 并且是不可能的,因为第一个 res.json 开始发送结果给用户。我想你想用 "data" 渲染 all_categories 所以你应该在将模板发送给用户之前在后端渲染(编译)模板。