Vue项目中的http请求统一管理

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: '/',
    assetsPublicPath: '/',
    proxyTable: {
        /open':{
            target:"https://www.sojson.com/",  // 目标
            changeOrigin: true, //是否跨域
            pathRewrite: {
                '^/open': '/open' 
            }
      }
    }
}
  this.$ajax({
              method: "post",
              url: '/open/api/weather/json.shtml'params: {
                city: '北京'
              }
            })then(({data}) => {
                if (data.message === "success") {
                  console.log(data.data)
                } 
              });

https://www.jianshu.com/p/495535eb063e vue项目使用webpack-dev-server调用第三方接口跨域配置

 

接口请求封装:http.js

import axios from 'axios'

const TIME_OUT_MS = 60 * 1000 // 默认请求超时时间

/*
 * @param response 返回数据列表
 */
function handleResults (response) {
    let remoteResponse = response.data
    var result = {
        success: false,
        message: '',
        status: [],
        errorCode: '',
        data: {
            total: 0,
            results: []
        }
    }
    if (remoteResponse.success) {
        result.data.results = remoteResponse.data
        result.data.total = remoteResponse.total
        result.success = true
    }
    if (!remoteResponse.success) {
        let code = remoteResponse.errorCode
        if (code === 400) {
            console.log('传参错误')
        }
        result.errorCode = remoteResponse.errorCode
        result.message = remoteResponse.message
    }
    return result
}

function handleUrl (url) {
    url = BASE_URL + url    
// BASE_URL是接口的ip前缀,比如http:10.100.1.1:8989/
    return url
}

/*
 * @param data 参数列表
 * @return
 */
function handleParams (data) {
    return data
}

export default {
    /*
     * @param url
     * @param data
     * @param response 请求成功时的回调函数
     * @param exception 异常的回调函数
     */
    post (url, data, response, exception) {
        axios({
            method: 'post',
            url: handleUrl(url),
            data: handleParams(data),
            timeout: TIME_OUT_MS,
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(
            (result) => {
                response(handleResults(result))
            }
        ).catch(
            (error) => {
                if (exception) {
                    exception(error)
                } else {
                    console.log(error)
                }
            }
        )
    },
    /*
     * get 请求
     * @param url
     * @param response 请求成功时的回调函数
     * @param exception 异常的回调函数
     */
    get (url, response, exception) {
        axios({
            method: 'get',
            url: handleUrl(url),
            timeout: TIME_OUT_MS,
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then(
            (result) => {
                response(handleResults(result))
            }
        ).catch(
            (error) => {
                if (exception) {
                    exception(error)
                } else {
                    console.log(error)
                }
            }
        )
    },
    /*
     * 导入文件
     * @param url
     * @param data
     * @param response 请求成功时的回调函数
     * @param exception 异常的回调函数
     */
    uploadFile (url, data, response, exception) {
        axios({
            method: 'post',
            url: handleUrl(url),
            data: handleParams(data),
            dataType: 'json',
            processData: false,
            contentType: false
        }).then(
            (result) => {
                response(handleResults(result, data))
            }
        ).catch(
            (error) => {
                if (exception) {
                    exception(error)
                } else {
                    console.log(error)
                }
            }
        )
    },
    /*
     * 下载文件用,导出 Excel 表格可以用这个方法
     * @param url
     * @param param
     * @param fileName 如果是导出 Excel 表格文件名后缀最好用.xls 而不是.xlsx,否则文件可能会因为格式错误导致无法打开
     * @param exception 异常的回调函数
     */
    downloadFile (url, data, fileName, exception) {
        axios({
            method: 'post',
            url: handleUrl(url),
            data: handleParams(data),
            responseType: 'blob'
        }).then(
            (result) => {
                const excelBlob = result.data
                if ('msSaveOrOpenBlob' in navigator) {
                    // Microsoft Edge and Microsoft Internet Explorer 10-11
                    window.navigator.msSaveOrOpenBlob(excelBlob, fileName)
                } else {
                    const elink = document.createElement('a')
                    elink.download = fileName
                    elink.style.display = 'none'
                    const blob = new Blob([excelBlob])
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    document.body.removeChild(elink)
                }
            }
        ).catch(
            (error) => {
                if (exception) {
                    exception(error)
                } else {
                    console.log(error)
                }
            }
        )
    },
    uploadFileFormData (url, data, response, exception) {
        axios({
            method: 'post',
            url: handleUrl(url),
            data: data,
            timeout: TIME_OUT_MS,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(
            (result) => {
                response(handleResults(result))
            }
        ).catch(
            (error) => {
                if (exception) {
                    exception(error)
                } else {
                    console.log(error)
                }
            }
        )
    }
}

接口api统一封装: ports.js

export default {
    manage: {
        register: '/manage/company/register', // 注册接口
        login: '/manage/company/login', // 登录
        logout: '/manage/company/loginOut' // // 退出
    },
    pwd: {
        sendEmail: '/manage/user/sendEmail',
        resetPwd: '/manage/user/passwordReset'
    }
}

引入和定义方式:main.js中

import http from 'http.js'
import ports from 'ports'
 Vue.prototype.http = http
 Vue.prototype.ports = ports

使用 方式:组件内

             this.http.post(this.ports.manage.login, {
                    userAccount: 'test',
                    userPassword: '111111',
                    cert: '1111111111'
                }, res => {
                    if (res.success) {
                       // 返回正确的处理
                    } else {
                      // 返回错误的处理 
                    }
                })

https://www.jianshu.com/p/72d911b6d61d vue-cli项目中axios接口封装以及api的统一管理

 

posted @ 2019-06-25 08:03  BloggerSb  阅读(2554)  评论(0编辑  收藏  举报