繁体   English   中英

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

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

如何将响应值access_token返回到变量以在其他地方使用? 如果我尝试在res.on('data')侦听器之外记录它的值,它会产生未定义的结果。

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_token}`); 问题在于尝试提取此值以在其他地方使用。 而不是必须使用HTTP调用将每个新函数封装在另一个调用中,以取代它并在它可以继续之前为其提供响应。 这有点像在 NodeJS 中强制执行同步性。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM