Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return response from http module in Node.js?

How do I return the response value, access_token, to a variable for use elsewhere? It yields undefined if I try to log its value outside of res.on('data') listener.

const http = require('http');
const authGrantType = 'password';
const username = '[The username]';
const password = '[The password]';
const postData = `grant_type=${authGrantType}&username=${username}&password=${password}`;
const options = {
  hostname: '[URL of the dev site, also omitting "http://" from the string]',
  port: 80,
  path: '[Path of the token]',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  }
};
const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`); // Print out the status
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`); // Print out the header
  res.setEncoding('utf8');
  res.on('data', (access_token) => {
    console.log(`BODY: ${access_token}`); // This prints out the generated token. This piece of data needs to be exported elsewhere
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});
req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// write data to request body
req.write(postData);
req.end();

The token value is logged to the console by the line that reads: console.log(`BODY: ${access_token}`); The issue is with trying to extract this value to be used elsewhere. Rather than having to encapsulate every new function with an HTTP call inside the other call that was required to supersede it and provide it with a response before it could continue. It's sort of enforcing synchronicity in NodeJS.


1 Answers

You should encapsutale your code with a promise

return new Promise((resolve, reject) => {
        const req = http.request(options, (res) => {
            res.setEncoding('utf8');
            res.on('data', (d) => {
              resolve(d);
            })
        });

        req.on('error', (e) => {
            reject(e);
        });

        req.write(data);
        req.end();
    })
like image 195
Geraldo Salazar Avatar answered Feb 01 '26 11:02

Geraldo Salazar