Vue axios跨域

255 阅读1分钟

前提

使用vue-cli 4.5

使用webstorm创建vue项目

安装axios

npm install axios --save

main.js使用axios

  import axios from 'axios'
//绑定到Vue原型上
Vue.prototype.axios = axios
//在引用的时候使用 this.axios

跨域

新建vue.config.js配置文件

module.exports = {
    devServer: {
        proxy: {
            //名字可以自定义,这里我用的是api
            '/api': {
                target: 'http://localhost:8087',//设置你调用的接口域名和端口号
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
};

main.js

axios.defaults.baseURL = 'api';

调用

created() {
  this.axios.get('/index').then((response) => {
    console.log(response);
  }).catch((err) => {
    console.log(err);
  })
}

注意

需要把vue.js.config放在根目录下

image.png

在我将vue.js.config放在src目录下时,并不能被识别到。