node.js的http请求失败发送后无法设置标头 [英] http request with node.js fail Can\'t set headers after they are sent

查看:184
本文介绍了node.js的http请求失败发送后无法设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用https / http请求服务器并在网页中显示结果。
它作为服务器上的脚本工作但失败了,我用get请求返回结果。

I try to request a server with https/http and display the result in a web page. It's work as a script on a server but fail with i return the result with a get request.

var express = require('express');
var app = express();
var port = 1337;
var https = require('https');

app.get('/', function(req, response, next) {
    doRequest(function(resp){
        response.send("response" + resp); // FAIL ON REQUEST !
    });
});
function doRequest(callback){

    var post_data"query=test";
    var post_options = {
        host: 'mySite.com',
        path: '/path/to/source',
        method: 'POST',
        secureProtocol: 'SSLv3_method'
    };

    // Set up the request
    var post_req = https.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(chunk);
        });
    });

    // post the data
    post_req.write(post_data);
    post_req.end();
}

 doRequest(console.log); // WORKS !

我收到此错误:

http.js:707
    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:707:11)
    at ServerResponse.res.set.res.header (/node_modules/express/lib/response.js:564:10)
    at ServerResponse.res.contentType.res.type (/node_modules/express/lib/response.js:434:15)
    at ServerResponse.res.send (/node_modules/express/lib/response.js:114:43)

我将Express 4与节点v0.10.15一起使用。

I use Express 4 with node v0.10.15.

推荐答案

JavaScript是异步的,所以

JavaScript is asynchronous so

// post the data
post_req.write(post_data);
post_req.end();

最有可能在执行之前执行

Will most likely be executed before

// Set up the request
var post_req = https.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        callback(chunk);
    });
});

结束,导致你的逻辑失败。

Is finished, causing your logic to fail.

这篇关于node.js的http请求失败发送后无法设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆