Error Can't set headers after they are sent

               

问题描述:

 系统:Windows 7 x64

 Node.js版本:版本是:v4.2.4 LTS

 安装过程参考:《Node.js入门》Windows 7下Node.js Web开发环境搭建笔记

 一段后端模拟HTTP请求的代码出现以下错误:Error: Can't set headers after they are sent.

 如下图:

 

相关代码:

app.get('/trans', function (req, res) var body = ''//这是需要提交的数据 params = { 'source':'en', 'target':'es', 'text':'hello'var data = qs.stringify(params);  http.get("https://gateway.watsonplatform.net/language-translation/api/v2/translate?" + data, function(gres) {   console.log("Got response: " + gres);   gres.on('data',function(d){   body += d;   }).on('end', function(){    //console.log(gres.headers);    console.log(body);    res.send(body);   }); }).on('error', function(e) {   console.log("Got error: " + e.message);  }); res.send(body);});
问题原因:

出现此错误的原因是因为

http.get
中的响应代码是异步的,

但在它响应之前,也就是最下面的一句“res.send(body);”已经把响应流关闭了。

解决方法:

将最下面的一句“res.send(body);”注释了就OK了。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值