如何从Node.js中的http模块返回响应?

如何从Node.js中的http模块返回响应?,node.js,asynchronous,callback,connect,asynccallback,Node.js,Asynchronous,Callback,Connect,Asynccallback,如何将响应值access\u token返回给变量以供其他地方使用?如果我尝试将其值记录在res.on('data')listener之外,则会产生未定义的值 const http = require('http'); const authGrantType = 'password'; const username = '[The username]'; const password = '[The password]'; const postData = `grant_type=${authG

如何将响应值access\u token返回给变量以供其他地方使用?如果我尝试将其值记录在
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();

令牌值通过以下行记录到控制台:
console.log(`BODY:${access\u token}`)问题在于试图提取此值以在其他地方使用。而不是必须用一个
HTTP
调用将每个新函数封装在另一个调用中,该调用是替换它所必需的,并在继续之前向它提供响应。这在某种程度上加强了NodeJ中的同步性。

你应该用承诺来封装你的代码

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();
    })

您是否尝试将其存储在变量中?是的,我存储了一个变量的access_令牌并将其记录到控制台,它的读数为undefined。我甚至试过var obj={};并简单地向obj添加了访问令牌。仍然以同样的问题回应。也许我遵循的程序是不正确的。不太确定。声明
var testVar
const req=..
上方。然后do
testvar=access\u令牌
res.on('data',…)
中尝试了一下。当我记录testVar的值时,它的读数是未定义的。这很奇怪,尝试将
const-req=…
更改为
var-req=…
,看看是否有效