think-fetch是Thinkjs提供的访问外部接口的模块,使用该模块可以很方便的访问外部接口同时做到同步。
相关连接:
https://github.com/thinkjs/think-fetch
https://thinkjs.org/zh-cn/doc/3.0/service.html
使用:
Install
$ npm install think-fetch --save
How to use
config file src/config/extend.js
const fetch = require('think-fetch');
module.exports = [
fetch, // HTTP request client.
];
Methods in Controller
module.exports = class extends think.Controller {
async indexAction () {
// plain text or html
const text = await this.fetch('https://github.com/').then(res => res.text());
// json
const json = await this.fetch('https://api.github.com/repos/thinkjs/think-fetch').then(res => res.json());
// post
const body = await this.fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' }).then(res => res.json());
// stream
const res = await this.fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
// post with stream from file
const stream = fs.createReadStream('input.txt');
const result = this.fetch('http://httpbin.org/post', { method: 'POST', body: stream }).then(res => res.json());
}
}
相比较使用http模块,这个更加方便。在这里做个记录。