javascript - Node.js JSON header

标签 javascript json node.js routes

我正在使用这个node.js 服务器应用程序,它具有用于自制 REST API 和服务静态页面的路由。当它提供静态页面时,我没有收到任何错误,但是当它提供来 self 的 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 数据,我现在只是在搞乱它:)

问题:如何消除上述控制台错误?

最佳答案

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

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

关于javascript - Node.js JSON header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34825860/

相关文章:

javascript - 从 IndexedDB 检索数据并显示

json - 如何从查询中返回一个 json 数组?

javascript - 低db : update record at index N

node.js - 如何使用 Node 配置ssl

node.js - 为什么 JSZip 不能创建 blob 文件?

javascript - 本地存储问题

JavaScript - 去除重复算法效率

javascript - 我想转换一个巨大的 excel 工作簿(带有多个选项卡)和隐藏在网页上的几列和几行

java - 使用简单的json,将包含json数组的json对象转换为字符串数组(在java中)

javax.ws.rs : What is Actually Returned by a Method