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

标签 node.js asynchronous callback asynccallback node.js-connect

如何将响应值 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();

token 值通过以下行记录到控制台:console.log(`BODY: ${access_token}`); 问题在于尝试提取此值以在其他地方使用。而不必使用 HTTP 调用将每个新函数封装在另一个调用中,该调用需要取代它并在继续之前为其提供响应。这有点强制 NodeJS 中的同步性。

最佳答案

您应该用 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();
    })

关于node.js - 如何从 Node.js 中的 http 模块返回响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276852/

相关文章:

javascript - 异步Ajax,具体是怎么回事?

c++ - CALLBACK DialogProc()定义中uMsg参数是什么意思

javascript - 如何将嵌套回调转换为 promise

javascript - NodeJS - 回调未执行

asynchronous - VueJs 子组件 Prop 不会立即更新

javascript - 在 Cordova 中使用 require 加载模块

node.js - 无法从 Lambda 调用 AppSync GraphQL api : TypeError: Cannot read property 'match' of null

javascript - 将 set-cookie header 发送到 node.js 中的重定向 url

C# Azure上传文件错误指定的blob或 block 内容无效

javascript - 无法通过 HTTP 请求将对象从客户端 JS 发送到 Node JS