当前位置:网站首页>TS encapsulation request

TS encapsulation request

2022-06-23 14:24:00 Qinghua side dish

import axios, {
     AxiosRequestConfig } from 'axios'
import {
     Toast } from 'vant'

const instance = axios.create({
    
  baseURL: '',
  timeout: 30000,
  withCredentials: false,
})

//interceptors by axios Interceptor , effect :
//1.  Modify some configuration items of the request header 
//2.  Add some requested icons to the request process 
//3.  Add parameters to the request 
instance.interceptors.response.use(
  response => {
       
    if (response.status === 200 || response.data.data.code === 200 ) {
    
      return response.data
    }
    return response
  },
  error => {
    
    const {
     response } = error
    // console.log("response---:",response)
    let message = ' Network error '
    if (response && response.data) {
    
      if (response.data.message) {
    
        message = response.data.message
      } else if (response.data.data){
    
        message = response.data.data.message
      }
    }
    Toast(message)
    return Promise.reject(error)
  },
)

/** *  ordinary  get  request , take  params  Take as the second parameter , And  post  Unified  * @param url * @param params * @param otherConfig * @returns */
export const get = (
  url: string,
  params?: Record<string, unknown>,
  // Allow before sending to server , Modify request data , Can only be used in  'PUT', 'POST'  and  'PATCH'  These request methods .
  // The function in the following array must return a string , or  ArrayBuffer, or  Stream.
  // Pass on to  then/catch  front , Allow modification of response data 
  otherConfig?: Omit<AxiosRequestConfig, 'params'>,
) => {
    
  return instance.get(url, {
    
    ...(otherConfig || {
    }),
    params: params || {
    },
  })
}

export default instance

Use :

import request from './request'
import {
     hosts, prefix } from '@/const/hosts'

export const getNearCityByName = (cityName: string) => {
    
  return request.get(`${
      hosts.qdfront}/getNearCityByName?cityName=${
      encodeURI(cityName)}`)
}
原网站

版权声明
本文为[Qinghua side dish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231330411210.html