简体   繁体   English

如何在 koa 中使用“http”模块?

[英]How can I use the "http" module in koa?

I am trying to use http.request on node using the koajs framework.我正在尝试使用 koajs 框架在节点上使用 http.request。 Is there a way I can utilize it as show below?有没有一种方法可以使用它,如下所示?

var http = require('http');

var result = yield http.request(options);

Presumably the problem you're facing is that http.request takes a callback rather than returning a promise, so you can't yield it from koa.大概您面临的问题是http.request接受回调而不是返回承诺,因此您无法从 koa 中yield它。 You need to wrap http.request in a function that returns a promise and hook the promise resolve into the callback, while also hooking the promise reject into the error handler.您需要将http.request包装在一个返回承诺的函数中,并将承诺解析挂钩到回调中,同时还将承诺拒绝挂钩到错误处理程序中。

function request(opts, body) {
  return new Promise((resolve, reject) => {
    body.pipe(http.request(opts, resolve))
    .on('error', reject);
  });
}

...later in your koa function... ...稍后在您的 koa 函数中...

var response = yield request(opts, body);

There are so many possible variations on this that I couldn't come close to listing them all, but that's the basic idea :)这有很多可能的变化,我无法将它们全部列出来,但这是基本思想:)

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

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