0

I'm using this code to make an HTTP request to my own server. I'm getting the appropriate response in chunk.

http.createServer(function (req, res) {
    var options = {
                    host: '<my ip>',
                    port: 8080,
                    method: 'GET',
                    path: '/content?data='+somedata
                };
    var call = http.request(options, function(res){
        res.setEncoding('utf8');                
        res.on('data', function(chunk){
            console.log("got response"+chunk);
        });
    }).on("error", function(e){
        console.log("Got error: " + e.message);
    });
    call.end();
}).listen(3000);

My question is how I can print this chunk to my browser?

1
  • sorry I'm quite new to node.js. I was unaware about the scope of variables. Commented Dec 22, 2015 at 15:40

2 Answers 2

2

Change one of your two res variables to have a different name. At the moment the response to your request is masking the response you are trying to make.

Then:

response.write(chunk);

See also: https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback

Sign up to request clarification or add additional context in comments.

3 Comments

var call = http.request(options, function(response){ response.setEncoding('utf8'); response.on('data', function(chunk){ //do something with chunk //console.log("got response"+chunk); //finaldata = chunk; response.write(chunk); }); }).on("error", function(e){ console.log("Got error: " + e.message); }); Gives me response.write is not a function.
@AakshayeMGaikar — That's because you're trying to write to the wrong response (i.e. the one you got back from your request, not the one your server is trying to make). You have to use the outer response object.
Thanks! I'm still quite new to Node.js. It worked for me now.
0
res.write(chunk);

also don't forget to end first call, so the browser will know the request has ended.

res.end("success");

1 Comment

Thanks! I'm still quite new to Node.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.