Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request 搞那么麻烦干嘛?简化呢? #317

Open
carveybunt opened this issue Mar 24, 2023 · 0 comments
Open

Request 搞那么麻烦干嘛?简化呢? #317

carveybunt opened this issue Mar 24, 2023 · 0 comments

Comments

@carveybunt
Copy link

carveybunt commented Mar 24, 2023

不是 umi4 选用默认的 axios?我看了下代码,貌似都没使用 Promise。作为一个从 vuereact 的新手来说,设置也太复杂?相对于我以前用 axios 部分代码如下:

// request.ts
const api = axios.create({
  baseURL:
    import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true'
      ? '/proxy/'
      : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 1000 * 60,
  responseType: 'json',
})

// 请求拦截器
api.interceptors.request.use((request) => {
  // 全局拦截请求发送前提交的参数
  const settingsStore = useSettingsStore()
  const userStore = useUserStore()
  // 设置请求头
  if (request.headers) {
    request.headers['Accept-Language'] = xxxx
    if (userStore.isLogin) {
      request.headers.Authorization = `Bearer xxxx`
    }
  }
  // 是否将 POST 请求参数进行字符串化处理
  if (request.method === 'post') {
    // request.data = qs.stringify(request.data, {
    //   arrayFormat: 'brackets',
    // })
  }
  return request
})

api.interceptors.response.use(
  (response: any) => {
    const status = response.data.status
    const message = response.data.message
    if (status === 200 || status === 201) {
      if (message.includes('xxxxxxx')) {
        ElMessage.error(message)
        return Promise.reject(response.data)
      }
    } else if (status === 422) {
      ElMessage.warning(message)
      return Promise.reject(response.data)
    } else if (status === 402 || status === 401) {
      ElMessage.warning(message)
      toLogin()
    } else {
      toLogin()
    }
    return Promise.resolve(response.data)
  },
  (error) => {
    let message = error.message
    if (message === 'Network Error') {
      message = '后端网络故障'
    } else if (message.includes('timeout')) {
      message = '接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`
    }
    ElMessage({
      message,
      type: 'error',
    })
    return Promise.reject(error)
  },
)

使用如下:

const id:string = 'uuid-xxx-yyy……'
api.get('/xxx')
api.get(`/xxx/${id}`)
api.put(`/xxx${id}`, data:any)
api.delete(`/xxx/${id}`)

相对于umi request 文档方便多了啊。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant