有时我在尝试使用请求模块获取请求时出错 码: const request = require('request');
getRequest("sitelink", {'Content-Type': 'application/json'}, null, proxy,
function(data, res){
log(data);
});
function getRequest(url, headers, setEncoding, proxy, onResult) {
var r = request;
if(proxy != null) r = request.defaults({'proxy':'http://' + proxy});
else r = request;
r({method: 'GET', url: url, headers: headers, encoding: (setEncoding == null ? 'UTF-8' : setEncoding)},
function (error, response, body) {
if (!error && response.statusCode == 200) {
onResult(body, response);
return;
} else log(error);
});
};
错误日志:
> Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
> to the client
> at ServerResponse.setHeader (_http_outgoing.js:469:11)
> at ServerResponse.header (/root/bot/node_modules/express/lib/response.js:767:10)
> at ServerResponse.send (/root/bot/node_modules/express/lib/response.js:170:12)
> at /root/bot/start.js:1381:12
> at Request._callback (/root/bot/start.js:1503:4)
> at Request.self.callback (/root/bot/node_modules/request/request.js:185:22)
> at Request.emit (events.js:182:13)
> at Request.EventEmitter.emit (domain.js:442:20)
> at Request.<anonymous> (/root/bot/node_modules/request/request.js:1161:10)
> at Request.emit (events.js:182:13)
答案 0 :(得分:1)
当您的应用通过HTTP对客户端进行响应时,会发生此错误,并且您尝试两次发送响应/响应标头。发送响应后,连接将关闭。 对于给定的http请求,您只能发送一次。您可以保持连接打开并发送更多数据,但是不能再次发送响应头。