小程序封装axios请求

封装axios

import {
      getStorageSync, clearStorage } from 'remax/wechat';
import axios from 'axios/dist/axios.min';
import mpAdapter from "axios-miniprogram-adapter";//使用模块
import {
      showToast } from 'remax/wechat';

const baseURL = process.env.NODE_ENV === 'development' ? 'https://test.*****.cn/api' : 'https://tt.****.cn/api';
const service = axios.create({
     
  adapter: mpAdapter,
  baseURL
});

// 封装令牌超时
/***
 *
 * @param error
 * @returns
 * code: "token_not_valid"
 *  detail: "Given token not valid for any token type"
 */

const err = (error) => {
     
  if (error.response) {
     
    if (error.response.status === 401) {
     
      showToast({
      title: '登录已失效,请重新登录', icon: 'none' }).catch();
      clearStorage().catch();
    }
  }
  return Promise.reject(error);
};

service.interceptors.request.use(
  config => {
     
    try {
     
      let token = getStorageSync('token');
      if (token) {
     
        config.headers.Authorization = `Bearer ${
       token}`;
      }
    } catch (e) {
     
      // Do something when catch error
    }
    return config;
  },
  error => {
     
    return Promise.reject(error);
  }
);

// http response 拦截器
service.interceptors.response.use(
  (response) => {
     
    return response;
  }, err);
export default service;

封装接口中使用

import http from '../utils/http';
export function code (data) {
     
  return http({
     
    url: '/code',
    data
  });
}

使用

import {
      code } from "../../../api/user";

//使用
code(value).then((res) => {
     
   if (res.status === 200) {
     
 }).catch();

你可能感兴趣的:(小程序,reactjs,javascript)