node.js - 如何将异步等待与 https 发布请求一起使用

标签 node.js https request node-modules

我正在寻找将 async/await 与 https post 一起使用的方法。请帮帮我。我已经在下面发布了我的 https 帖子代码片段。如何使用异步等待。

const https = require('https')

const data = JSON.stringify({
  todo: 'Buy the milk'
})

const options = {
  hostname: 'flaviocopes.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
})

req.on('error', (error) => {
  console.error(error)
})

req.write(data)
req.end()

最佳答案

基本上,您可以编写一个返回 Promise 的函数。然后你可以使用 async/await有了那个功能。请参阅以下内容:

const https = require('https')

const data = JSON.stringify({
  todo: 'Buy the milk'
});

const options = {
  hostname: 'flaviocopes.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  },
};

async function doSomethingUseful() {
  // return the response
  return await doRequest(options, data);
}


/**
 * Do a request with options provided.
 *
 * @param {Object} options
 * @param {Object} data
 * @return {Promise} a promise of request
 */
function doRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      res.setEncoding('utf8');
      let responseBody = '';

      res.on('data', (chunk) => {
        responseBody += chunk;
      });

      res.on('end', () => {
        resolve(JSON.parse(responseBody));
      });
    });

    req.on('error', (err) => {
      reject(err);
    });

    req.write(data)
    req.end();
  });
}

关于node.js - 如何将异步等待与 https 发布请求一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52951091/

相关文章:

node.js - 在 Chromium 中传递 "Your connection is not private"页面

用于 HTTPS 连接的 Powershell SSL TLS 密码套件

ssl - CSR 文件丢失但有 KEY 文件和 CRT 文件

VBS 中的 HTTP GET

node.js - 如何使用 request nodejs 模块创建变量文件名?

php - AJAX 请求 PHP 脚本循环

node.js - Web3 通过钱包地址获取所有代币

node.js - NativeScript 类型错误 : Cannot read property 'version' of undefined

php - 从 HTTPS 重定向到 HTTP

node.js - 仅使用 Grunt 查找并复制 CSS 文件中引用的图像