Horia
Horia

Reputation: 2982

How to store on a variable the output from a request?

I am having a simple http server that returns a message based on the message returned from another request.

const http = require('http');
const app = new http.Server();

var message = 'm1';

const options = {
  method: 'GET',
  hostname: '<some-hostname>',
  port: <some_port>
};

app.on('request', (rq, rs) => {
    const m2req = http.request(options, (res) => {
      res.on('data', (d) => {
        message = d;
        process.stdout.write(message);//this prints m2, which is correct
      })
    })

    m2req.on('error', (error) => {
      console.error(error)
    })
    m2req.end();

    rs.writeHead(200, { 'Content-Type': 'text/plain' });
    rs.write(message);// this should print 'm2' but prints 'm1'
    rs.end('\n');

});

app.listen(<some_port>, () => {
});

What is the right way so my server prints m2 instead of m1?

Thank you for your time.

Upvotes: 0

Views: 169

Answers (2)

Deepak
Deepak

Reputation: 1433

Nodejs is asynchronous, you have to use like this below

app.on('request', (rq, rs) => {
    const m2req = http.request(options, (res) => {
        var data = []
        res.on("data", (d) => { data.push(d) })
        res.on('end', () => {
            rs.writeHead(200, { 'Content-Type': 'text/plain' });
            rs.write(Buffer.concat(data).toString());// this should print 'm2' but prints 'm1'
            rs.end('\n');
        })
    })

    m2req.on('error', (error) => {
      console.error(error)
    })
    m2req.end();

});

Upvotes: 1

Nithya Rajan
Nithya Rajan

Reputation: 4884

In your code, you are requesting another service, which is an asynchronous operation. so the variable message is still "m1", because before the service returns the value your res.write(message) executes so it's still "m1". You should write res.send() res.write() res.writeHead inside the callback of res.on

const http = require('http');
const app = new http.Server();

var message = 'm1';

const options = {
  method: 'GET',
  hostname: '<some-hostname>',
  port: <some_port>
};

app.on('request', (rq, rs) => {
    const m2req = http.request(options, (res) => {
      res.on('data', (d) => {
        message = d;
        process.stdout.write(message);//this prints m2, which is correct

        rs.writeHead(200, { 'Content-Type': 'text/plain' });
        rs.write(message);// this should print 'm2' but prints 'm1'
        rs.end('\n');
      })
    })

    m2req.on('error', (error) => {
      console.error(error)
    })
    m2req.end();



});

app.listen(<some_port>, () => {
});

Upvotes: 1

Related Questions