【问题标题】:How to return response from http module in Node.js?如何从 Node.js 中的 http 模块返回响应?
【发布时间】:2019-02-16 00:19:13
【问题描述】:

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

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 中强制同步。

【问题讨论】:

  • 您是否尝试将其存储在变量中?
  • 是的,我将 access_token 存储到一个变量并将其记录到控制台,它读取未定义。我什至试过 var obj = {};并简单地将 access_token 添加到 obj 中。仍然回应同样的问题。也许我遵循的程序不正确。不太确定。
  • 在const req = .... 上方声明var testVar;。然后在res.on('data', ...) 中执行testvar = access_token;
  • 刚刚试过。当我记录 testVar 的值时,它显示为 undefined。
  • 这很奇怪,尝试将const req = ... 更改为var req = ... 看看是否有效

标签: node.js asynchronous callback connect asynccallback


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 2012-01-17
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多