【Taro开发】-带token网络请求封装(四)

2,940 阅读2分钟

Taro小程序开发

系列文章的所有文章的目录

【Taro开发】-初始化项目(一)

【Taro开发】-路由传参(二)

【Taro开发】-taro-ui(三)

【Taro开发】-带token网络请求封装(四)

【Taro开发】-自定义导航栏NavBar(五)

【Taro开发】-formData图片上传组件(六)

【Taro开发】-封装Form表单组件和表单检验(七)


前言

基于Taro的微信小程序开发,主要组件库为Taro-ui Taro-ui:基于 Taro 开发 UI 组件 一套组件可以在 微信小程序,支付宝小程序,百度小程序,H5 多端适配运行(ReactNative 端暂不支持) 提供友好的 API,可灵活的使用组件


提示:以下是本篇文章正文内容,下面案例可供参考

1.新建文件夹及文件

在这里插入图片描述

2.apiConfig

let baseUrlPrefix = ''
const env = process.env.NODE_ENV === 'development' ? 'development' : 'production'
console.log('编译环境:',process.env.NODE_ENV)
switch (env) {
  case 'development':
    baseUrlPrefix = 'http://...'
    break
  case 'production':
    baseUrlPrefix = 'https://...'
    break
}

const api = {
  baseUrl: baseUrlPrefix,
//其他相关变量
}

export default api

3.httpService

import Taro from '@tarojs/taro';
import apiConfig from './apiConfig'

//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const { method, data, url } = requestParams
  let token = Taro.getStorageSync('TOKEN')//拿到本地缓存中存的token
  requestParams.header = {
    ...requestParams.header,
    Authorization: 'Bearer ' + token //将token添加到头部
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const request = async (method, url, params) => {
  //由于post请求时习惯性query参数使用params,body参数使用data,而taro只有data参数,使用contentType作为区分,因此此处需要做一个判断
  let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: false,
    url: apiConfig.baseUrl + url,
    data: params && (params?.data || params?.params),
    header: {
      'content-type': contentType,
    },
    success(res) {
    //根据不同返回状态值3进行操作
      switch (res?.statusCode) {
        case 503: {
     	  ...
          break;
        }
		...
        default:
          break;
      }
    },
    error(e) {
      console.log('api', '请求接口出现问题', e);
    }
  }
  const resp = await Taro.request(option);
  return resp.data;//根据个人需要返回
}

export default {
  get: (url, config) => {
    return request('GET', url, config);
  },
  post: (url, config) => {
    return request('POST', url, config);
  },
  put: (url, config) => {
    return request('PUT', url, config);
  },
  delete: (url, config) => {
    return request('DELETE', url, config);
  },
  patch: (url, config) => {
    return request('PATCH', url, config);
  },
}

4.使用

index.js //可根据不同模块区分文件请求
import httpService from './httpService';

function getUser(id, params) {
  return httpService.get(`/user/${id}`, {
  	params
  })
}

export default {
  getUser
}
//页面文件使用
import service from "@/services";
service.getUser(1001,{...}).then(res=>console.log(res))