Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

怎么用koa发出一个请求呢?用request.get方法吗?怎么拿到响应呢? #21

Closed
zeyongTsai opened this issue Dec 18, 2015 · 4 comments

Comments

@zeyongTsai
Copy link

RT

@chouchou900822
Copy link

不太懂你的意思,是用http发请求吗,那和express的一样。request的话,看看这个,不知道是不是你想要的

var request = require("request");
var co = require("co");

function requestPromise(options) {
  return new Promise(function (resolve, reject) {
    request(options, function(err, response, body) {
      if (err) reject(err);
      resolve(body);
    });
  });
}
co(function* () {
  var body = yield requestPromise('http://www.baidu.com');
  console.log(body);
})

@zeyongTsai
Copy link
Author

非常感谢,我刚学nodejs后台相关的东西;然后看了koa的ctx相关的API,唯一发现一个get方法,但又苦于找不到该方法的使用;我以为可以这样:
app.use(route.get('/domain',function *(ctx){
this.request.get('http://www.baidu.com',function(e,r,b){
console.log(e,r,b);//not work
});
}));

但。。。
始终不明白koa在整个web服务中除了具备基本的接收/响应的功能外,还具备哪些能力,例如这个发出一个请求的功能,是需要引入request的吗还是koa本身就有?或者哪个中间件可以用?

@chouchou900822
Copy link

看文档

request.get(field)

这个是返回请求的header的某个属性信息的

router.get('/domain', function* () {
  console.log(this.request.headers);
  console.log(this.request.get('Connection'));
  this.body = 'end';
});

这样应该能看懂了
koa比较自由, 看https://github.com/base-n/koa-generator-examples/issues/19 这个issue就是讨论这个问题的。
像request,你可以选择像我上面这样用promise封装,或者用别人的用promise封装好的modules,比如
request-promise这种。

@zeyongTsai
Copy link
Author

@chouchou900822
恩,好的;十分感谢你帮我解惑; 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants