1.0.10 • Published 3 years ago

lbl-request v1.0.10

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

安装

npm install lbl-request

如何使用

// request.ts

import { Request, Result } from 'lbl-request'
import { AxiosRequestConfig, AxiosResponse } from 'axios'

export const request = new Request({
  // 业务域名
  baseURL: 'https://lbaxios.com/api',
  // 返回 json 的大小写转换:'pascal' | 'camel' | 'none'
  convertCase: 'camel',

  // 成功条件
  successCondition: (result: Result) => {
    return result.code === 0
  },

  // 发生异常时处理
  onError: (result: Result, toastError: boolean) => {
    console.log(`----- ${result.url} 接口报错 -----`)
    console.log(result)

    if (result.status === 401) {
      Util.toast.error('登录状态失效,请重新登录')
      setTimeout(() => {
        StoreUser.logout()
      }, 1000)
    } else if (toastError) {
      Util.toast.error(result.message)
    }
  },

  // 请求头混入
  mixinHeader: (config: AxiosRequestConfig, isBusinessDomain: boolean) => {
    if (!isBusinessDomain) return config

    const token = Util.token.getToken()
    if (token) {
      config.headers.common['Authorization'] = token
    }

    config.headers.common['Accept-Language'] = Util.i18n.getLang()
    return config
  },

  // 响应内容转换为 Result
  responseFormat: (result: Result, response: AxiosResponse) => {
    const data = response.data
    result.code = data.code
    result.message = data.message
    result.data = data.data
    return result
  }
})



// api/user.ts
import { request } from './request'

export async function login() {
  const res = await request.post('/user/login', {
    username: '123456',
    password: 123456
  })

  const { token } = res.hasSuccess()
  Util.token.setToken(token)
}
1.0.9

3 years ago

1.0.10

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago