nextjs 基于 isomorphic-unfetch 封装自己的请求库

封装是为了自己更好的玩耍,给大家参考一下,可根据自己的需求增加属性或方法~

第一步。封装自己的请求类【文件名:SelfFetch.js】

yarn add isomorphic-unfetch 或者 npm i isomorphic-unfetch --save

import fetch from "isomorphic-unfetch";

class SelfFetch {

  // 让每个promise请求都trycatch
  async baseMethod(fn) {
    if (fn) {
      try {
        const res = await fn;
        const data = await res.json();
        if (data.code === 0) {
          return data.data;
        } else {
          return '';
        }
      } catch (error) {
        return null;
      }
    }
  }

  async get(url) {
    const token = window.localStorage.getItem('token') || ''
    return await this.baseMethod(
      fetch(url, {
        headers: {
          Authorization: `Bearer ${token}`, // 带上token的地方
          'Content-Type': 'application/json'
        },
      })
    );
  }

  async post(url, options) {
   const token = window.localStorage.getItem('token') || ''
   const res = await this.baseMethod(
      fetch(url, {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(options),
      })
    );
    return res;
  }

  async put(url, options) {
    const token = window.localStorage.getItem('token') || ''
    const res = await this.baseMethod(
       fetch(url, {
         headers: {
           Authorization: `Bearer ${token}`,
           'Content-Type': 'application/json'
         },
         method: "Put",
         body: JSON.stringify(options),
       })
     );
     return res;
   }
}

export default SelfFetch;

第二步。封装自己的请求方法【文件名:service.js】

import SelfFetch from './SelfFetch';
const selfFetch = new SelfFetch();
const BaseUrl = '127.0.0.1:3000'

export async function getTopicsApi(options) {
  return await selfFetch.get(
    `${BaseUrl}/api/v1/topics?page=${options.page || 1}&size=${
      options.size || 10
    }`
  );
}

export async function loginApi(options) {
  return await selfFetch.post(`${BaseUrl}/api/login`, options);
}

export async function getUserInfoApi() {
  return await selfFetch.get(`${BaseUrl}/api/getUserInfo`);
}

export async function putQrcodeApi(qrcode) {
  return await selfFetch.put(`${BaseUrl}/api/v1/topics/${qrcode}`);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值