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}`);
}

版权声明:本文为qq_44685105原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。