基于axios封装接口访问

 1.封装

/**
 * axios方法的扩展,添加了结果处理的封装,用法与axios一致
 * 用法
 * import { request } from 'net'
 * 
 * request({
 *  baseURL: '',                    // http://...
 *  url: '/test',                   // http://10.206.228.248:3000/mock/35/test
 *  method: 'get',
 *  data: { id: '123' },
 *  mockData: { name: 'jack' },     // 返回此模拟数据
 *  callback: res => {  },          // 自定义返回操作
 *  headers: { 'token': 'abc' }     // 
 * }).then(json => {
 *  // console.log(josn)
 * })
 * 
 * 
 */
import axios from 'axios'
import { MessageBox, Toast, Indicator} from 'mint-ui'
// import Cookies from 'js-cookie'
import router from '../router'
import store from '../store'

axios.defaults.withCredentials = true; // 允许携带cookie
let reqId = 0
let baseURL = urlSrc // 来自public/url.js

function request(props) {
    // 如果使用mock数据,直接返回
    if (props.mockData) {
        return Promise.resolve({ ...props.mockData })
    }
    
    // 开发模式使用代理转发-
    if (process.env.NODE_ENV === 'development') {
        baseURL = 'http://localhost:8080'
    }
    // 默认值
    const dft = {
        baseURL,
        timeout: 10000,
        method: 'get', //
        callback: null,
        indicator: true, // 是否显示加载器
    }

    const config = { ...dft, ...props }
    config.headers =  {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Credentials': 'true',
        // '_TOKEN_KEY_': Cookies.get('_TOKEN_KEY_'),
        ...props.headers
    }
    
    // console.log(config)
    // get时候统一使用data代替params
    if (config.method.toUpperCase() === 'GET' && config.data) {
        config.params = { ...config.data, ...config.params }
    }
    // if (typeof config.data !== 'string') { config.data = JSON.stringify(config.data) }
    // if (config.mock) { config.baseURL = '' }
    if (config.indicator) { Indicator.open() }
    
    const pms = new Promise((resolve, reject) => {
        // console.log(`req${++reqId}:`, config)
        axios(config)
        .then(res => {
            const { status, data } = res
            // console.log(`res${++reqId}:`, res)
            const {
                errcode, data: d, errmsg, // jwt
                response, obj, errorCode, errorMessage, success, succ, msg, result } = data
            // 可能不同的接口返回的字段名称会是其中一个,从中选取不是undefined的那一个
            const [json] = [response, obj, result, d].filter(el => el != undefined)
            const [su] = [succ, success].filter(el => el != undefined)
            const [ms] = [msg, errmsg, errorMessage].filter(el => el != undefined)
            // console.log('su:', su)
            if (su == 'login') {
                // 前往登录
                Toast('请登录')
                const { path } = router.history.current
                if (path != '/checkMobile') {
                    // const phone = window.phone
                    // debugger
                    router.push({ path: '/checkMobile' })
                }
                return
            }
            // 如果有传入自定义callback,优先!
            if (config.callback) {
                config.callback(data)
                return
            }
            
            if (su == false || su == 'fail') {
                MessageBox.alert(`${ms}`, '提示')
                return
            }

            if (su == true || su == 'ok') {
                resolve(json)
                return
            }
            reject(res)
        })
        .catch(error => {
            console.log('err..:', error)
            const { status, data } = error.response || {}
            if (status > 300) {
                return Toast(`(${status})网络异常,请稍后再试。`)
            }
            if (status >= 500) {
                return MessageBox.alert(`(${status})服务器错误,请稍后再试。`, '提示' )
            }
            if (status === 404) {
                return MessageBox.alert(`(${status})地址错误。`, '提示')
            }
            MessageBox.alert(`请求发生错误,请稍后再试。`)
        }).finally(() => {
            Indicator.close()
        })
    })

    return pms
}
Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
    )
}
export { request, baseURL }

2.使用

request({
    // baseURL: 'http://10.206.228.248:3000/mock/35',
    url: '/pub/open/webQuery/queryVehicleList',
    method: 'post',
}).then(res => {
    const { typeMapLens = [] } = res
    this.vehicleTypeList = typeMapLens
    let obj = {}
    typeMapLens.forEach(el => {
        const lens = el.lens || []
        lens.forEach(len => {
            if (!obj[len]) { obj[len] = true }
        });
    })
    let list = Object.keys(obj).sort((p, n) => p - n)
    this.vehicleLengthList = list
}).catch(() => '')

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Nuxt.js 是一个基于 Vue.js 的开源框架,主要用于构建服务端渲染 (SSR) 的 Web 应用程序。而 axios 是一个基于 Promise 的 HTTP 库,可以用于浏览器和 Node.js 环境下的 HTTP 请求。在 Nuxt.js 中使用 axios,可以通过封装 axios 实例来统一处理 HTTP 请求,方便使用和维护。以下是一个简单的封装 axios 实例的示例代码: 1. 在 plugins 目录下创建一个 axios.js 文件 ```javascript import axios from 'axios' const axiosInstance = axios.create({ baseURL: 'https://api.example.com', // 接口的基础路径 timeout: 10000 // 请求超时时间 }) // 请求拦截器 axiosInstance.interceptors.request.use(config => { // 在发送请求之前做些什么 return config }, error => { // 对请求错误做些什么 return Promise.reject(error) }) // 响应拦截器 axiosInstance.interceptors.response.use(response => { // 对响应数据做些什么 return response.data }, error => { // 对响应错误做些什么 return Promise.reject(error) }) export default ({ app }, inject) => { // 将 axios 实例注入到 Vue 实例中 inject('axios', axiosInstance) } ``` 2. 在 nuxt.config.js 中引入插件 ```javascript export default { // ... plugins: [ '~/plugins/axios' ], // ... } ``` 3. 在组件中使用 axios ```javascript export default { async asyncData({ $axios }) { const data = await $axios.$get('/api/data') return { data } } } ``` 通过上述封装,可以在组件中通过 this.$axios 访问封装后的 axios 实例,方便统一处理请求和响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值