本文介绍了发送标头后无法设置.在第二次使用Node和Express调用REST API时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting below ERROR while making a RESTFUL API call created using Node and express,

注意:对于第一个调用,我得到了预期的JSON响应.尝试第二次打时出现此错误.

Note: For the 1st call i got JSON response as expected. When try to hit 2nd time i got this ERROR.

  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);
    });
  }
});

推荐答案

我找到了一种解决方法.将JSON响应转换为字符串后.奏效了.

I found a workaround. After converting JSON response to string. It worked.

res.send(JSON.stringify(data));

这篇关于发送标头后无法设置.在第二次使用Node和Express调用REST API时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:37