Thinks——进阶think-fetch的使用

本文详细介绍了Thinkjs框架下的think-fetch模块,该模块简化了外部接口的访问过程,支持同步请求,提供了多种请求方式如GET、POST,并能处理各种响应类型包括文本、JSON、流等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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模块,这个更加方便。在这里做个记录。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值