3

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.

6
  • have you tried storing it in a variable? Commented Sep 11, 2018 at 13:17
  • Yes, I stored access_token to a variable and logged it to the console, it read undefined. I even tried var obj = {}; And simply added access_token to obj. Still responds with the same issue. Perhaps the procedure that I followed was incorrect. Not quite sure. Commented Sep 11, 2018 at 13:21
  • declare var testVar; above the const req = ..... then do testvar = access_token; inside the res.on('data', ...) Commented Sep 11, 2018 at 13:23
  • Just tried that. When I log the value of testVar, it reads undefined. Commented Sep 11, 2018 at 13:26
  • thats strange, try changing const req = ... to var req = ... and see if that works Commented Sep 11, 2018 at 13:27

1 Answer 1

2

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();
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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