http request with node.js fail Can\\'t set hea

2019-07-07 11:42发布

问题:

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 !

I get this error:

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)

I use Express 4 with node v0.10.15.

回答1:

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.