【问题标题】:Node.js JSON headersNode.js JSON 标头
【发布时间】:2016-01-16 10:23:00
【问题描述】:

我正在玩弄这个 node.js 服务器应用程序,它具有用于自制 REST API 和服务静态页面的路由。当它为静态页面提供服务时,我没有收到任何错误,但是当它从我的 API 提供内容时,我在控制台中得到以下信息:

Error: Can't set headers after they are sent.
at SendStream.headersAlreadySent (C:\path_to_node_folder\node_modules\send\lib\send.js:302:13)
at SendStream.send (C:\path_to_node_folder\node_modules\express\node_modules\send\lib\send.js:490:17)
at C:\path_to_node_folder\node_modules\express\node_modules\send\lib\send.js:467:10
at FSReqWrap.oncomplete (fs.js:82:15)

我的路线:

module.exports = function(app) {
  "use strict";

  app.get('/api', function(req, res, next) {
    res.json({
      message : 'Welcome to the Angular Blog RESTful API'
    });
    next();
  });

  app.get('/api/article/:permalink', function(req, res, next) {
    res.json({
      message   : "Article retrieved",
      permalink : req.params.permalink
    });
    next();
  });

  app.post('/api/comment', function(req, res, next) {
    res.json({
      message : "save comment"
    });
    next();
  });

  app.use(function(req, res) {
    // use res.sendfile, as it streams instead of reading the file into memory.
    res.sendfile('./public_html/index.html');
  });
};

现在,请不要讨厌返回的 JSON 数据,我现在只是在搞乱它:)

问题:如何摆脱上述控制台错误?

【问题讨论】:

    标签: javascript json node.js routes


    【解决方案1】:

    您可以拨打res.json()next(),但不能同时拨打这两个电话。仅当您正在实现中间件或要将错误转发到错误处理程序时才调用 next()

    if (!req.query.userId) {
      return next(new Error('UserId is missing!'));
    }
    res.json({ message: "ok" });
    

    【讨论】:

    • 太棒了!谢谢你的解释:)
    猜你喜欢
    • 2019-10-17
    • 2015-08-18
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2016-12-10
    • 2013-08-10
    相关资源
    最近更新 更多