Fork me on GitHub

Vue-cli3.x中使用Axios发送跨域请求的配置方法

Vue-cli3.x中使用Axios发送跨域请求的配置方法

  1. 安装axios
npm i axios -s
  1. main.js中引入
    import axios from 'axios'
     //将axios挂载在Vue扩展上
     Vue.prototype.$http=axios
     //在其他地方使用只需使用 this.$http来代替axios;
     //配置baseUrl
     axios.defaults.baseURL = '/api'
    
  2. vue.config.js配置
    在devServer中加入
    proxy: {
           '/api': {
                 target: 'http://localhost:8888/EasyPicker',//请求的目标地址的BaseURL
                 changeOrigin: true, //是否开启跨域
                 pathRewrite: {
                     '^/api': '' //规定请求地址以什么作为开头
                 }
             }
         }
    
    配置完成后如下
    module.exports = {
     configureWebpack: {
         devServer: {
                 proxy: {
                     '/api': {
                         target: 'http://localhost:8888/EasyPicker',
                         changeOrigin: true, //是否跨域
                         pathRewrite: {
                         '^/api': '' //规定请求地址以什么作为开头
                         }
                     }
                 }
             }
         }
     }
    

完成上述配置后差不多算大功告成了,下面是请求示例


通过上述简单的配置即可完成跨域请求的发送,前后端分离开发中非常实用的技巧

posted @ 2019-07-08 13:17  粥里有勺糖  阅读(5854)  评论(0编辑  收藏  举报