3

在进行使用 Node 和 express 创建的 RESTFUL API 调用时,我遇到了错误,

注意:对于第一次通话,我得到了预期的 JSON 响应。当尝试第二次点击时,我得到了这个错误。

  http.js:704
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:704:11)
    at ServerResponse.res.setHeader (/Users/rain/node-js-sample/node_modules/express/node_modules/connect/lib/patch.js:62:20)
    at ServerResponse.res.header (/Users/rain/node-js-sample/node_modules/express/lib/response.js:280:8)
    at ServerResponse.res.json (/Users/rain/node-js-sample/node_modules/express/lib/response.js:135:8)
    at EventEmitter.<anonymous> (/Users/rain/node-js-sample/web.js:82:11)
    at EventEmitter.emit (events.js:117:20)

服务器代码,

app.get('/service/:id/:startDate/:endDate', function(req, res) {
  if(req.params.id.length <= 0 || req.params.startDate.length <= 0 || req.params.endDate.length <= 0) {
    res.statusCode = 404;
    res.send('Error 404: Invalid start date or end date provided');
  } else {
    rest.get("http://localhost:8080/service/" + req.params.chartId  + 
      "/" + req.params.startDate +
      "/" + req.params.endDate).on('complete', function(data, response) {
      console.log(data);
      res.json(data);
    });
  }
});
4

1 回答 1

1

我找到了解决方法。将 JSON 响应转换为字符串后。有效。

res.send(JSON.stringify(data));
于 2013-07-18T22:06:33.147 回答