vue封装axios请求

334 阅读2分钟

1.cdn引入axios

<script src="https://cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js"></script>

2.封装http.js文件 [放在untils文件中]

import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'

let vm = new Vue()
let baseURL
axios.defaults.timeout = 5000;                        //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json';        //配置请求头
//可以外部配置
if (process.env.NODE_ENV == "production") {
    if (ACTIVE_ENV_CONFIG === 'test') {//测试
       baseURL='xxx'
    } else if (ACTIVE_ENV_CONFIG === 'prod') { //生产
	   baseURL='xxx'
    } else { //开发
	   baseURL='xxx'
    }
} else {//本地 (可以不写,走proxy代理)
   // baseURL='xxx'
}
axios.defaults.baseURL = baseURL

//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
    //在发送请求之前做某件事
    config.validateStatus = function (status) {//状态码返回
        return status >= 200 && status < 300
    }
    return config;
}, (error) => {
    // console.log('错误的传参')
    return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
    //此处可以根据自己公司接口返回进行处理
    return res
}, (error) => {
    return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                //console.log(error)
                reject(error)
            })
    })
}
////返回一个Promise(发送get请求)
export function fetchGet(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, { params: param })
            .then(response => {
                resolve(response);
            }, err => {
                // console.log(err)
                reject(err)
            })
            .catch((error) => {
                // console.log(error)
                reject(error)
            })
    })
}
//返回一个Promise(发送put请求)
export function fetchPut(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                // console.log(err)
                reject(err);
            })
            .catch((error) => {
                // console.log(error)
                reject(error)
            })
    })
}
//返回一个Promise(发送delete请求)
export function fetchDelete(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, { params: params })
            .then(response => {
                resolve(response);
            }, err => {
                // console.log(err)
                reject(err);
            })
            .catch((error) => {
                // console.log(error)
                reject(error)
            })
    })
}

export default {
    fetchPost,
    fetchGet,
    fetchPut,
    fetchDelete
}

3.全局引入 [main.js中引入]

import http from '@/utils/http'

Vue.prototype.$http = http

4.使用

get请求:this.$http.fetchGet

post请求:this.$http.fetchPost

put请求:this.$http.fetchPut

delete请求:this.$http.fetchDelete

eg:

this.$http.fetchPost(`/api/v2/resource/image`, {
    resource_id: this.data.mediaUri,
    width: 0,
    height: 0
})
.then(res => {
  //接口返回数据处理
})

5.proxy代理 [config/index.js]

只需要加入以下文件内的proxy对象就行

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      proxy: { //匹配到 /api,代理到xxxx地址
        '/api': {
          target: 'xxxx',
          changeOrigin: true,
          pathRewrite: {
            '^/api': '/api'
          }
        }
      },
    },

    // Various Dev Server settings
    host: '0.0.0.0', //localhost// can be overwritten by process.env.HOST
    port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: false,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}