封装request

// src/utils/request.ts
import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios"
import { ElMessage } from "element-plus"
import { getToken, removeToken } from "@/utils/auth"

//创建axios实例对象,添加全局配置
const service = axios.create({
  baseURL: '/api', 
  timeout: 8000,
})

//请求拦截
service.interceptors.request.use((config: InternalAxiosRequestConfig): InternalAxiosRequestConfig<any> => {
  if (getToken()) {
    config.headers["Authorization"] = "Bearer " + getToken()
  }

  if (config.headers["Content-Type"] == "application/x-www-form-urlencoded") {
    config.data = JSON.stringify(config.data)
  }
  return config
})

// 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, status, statusText, config } = response
    if (status !== 200 || data.code !== 200) {
      if (data.code === 401) {
        // 未登陆
        ElMessage.error("未登陆")
        removeToken()
        location.reload()
      }
      ElMessage.error(data.message)
      return Promise.reject(data.message)
    }
    // 直接返回后端data的数据,后端数据格式{code:200, message:"", data: []}
    return data
  },
  (error) => {
    ElMessage.error("网络异常,请稍候再试")
    // 在响应错误的时候的逻辑处理
    return Promise.reject(error)
  }
)
export default service

使用拦截器

import request from "@/utils/request"
request.get(url[, config])
request.delete(url[, config])
request.head(url[, config])
request.options(url[, config])
request.post(url[, data[, config]])
request.put(url[, data[, config]])
request.patch(url[, data[, config]])
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐