3

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.

Thomas
  • 1,008
  • 3
  • 16
  • 34

1 Answers1

5

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.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
  • 2
    To be clear, Javascript is not asynchronous. The http request is performed async. The language has little to do with that other than it is best practice to code network requests with async patterns. – Todd Baur Jan 06 '15 at 13:22