axios处理跨域问题

首先npm安装好axios,其次在main.js中引入:css

import axios from 'axios'vue

Vue.prototype.$axios = axios //把axios挂载到vue的原型中,在vue中每一个组件均可以使用axios发送请求
Vue.prototype.HOME = '/api' //重要在于这里,Vue.prototype.HOME = '/api'是一个定值,默认指向localhost,全部修改指向路径为'/api',配置文件index.js定义的可跨域路径ios

第二步就是修改上述所说的config>index.js配置文件npm

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {     //axios跨域处理
      '/api': {       //此处并不是和url一致
        target:'http://192.168.2.80:8081/',
        changeOrigin:true, //容许跨域
        pathRewrite:{
          '^/api': ''
        }
      }
    }
}
....如下省略
}

最后就是在须要跨域的文件中操做了:json

created() {
      var url = this.HOME + '/index***ds/getFe***List';  //HOME变量为已挂载的可跨域域名,这里将其拼接完,成为一个完整路径
      this.$axios({  //this表明vue对象,以前在入口文件中把axios挂载到了vue中,因此这里直接用this.$axios调用axios对象
        method: 'post',
        url: url,
        data: {feedType: 1, page: 1, pagesize: 10}
      }).then(function (res) {
        console.log(res);
      }).catch(function (err) {
        console.log(err);
      })
    },
这样就能够成功跨域,拿到后台返回的数据了。

须要注意的是:在Vue项目中若是咱们修改了config里面的文件,请千万要从新启动项目,从新启动项目,从新启动项目,否则必定会报错。axios

固然,这只是在本地能够正常跨域访问接口,线上的话,还须要和后台协商处理api

升级到 Vue3 后,会发现 Vue2 中存放配置的 config 文件夹没有了,你们不要慌张。能够在 package.json 文件的同级目录下建立 vue.config.js 文件。给出该文件的基础配置:跨域

module.exports = {
    outputDir: 'dist',   //build输出目录
    assetsDir: 'assets', //静态资源目录(js, css, img)
    lintOnSave: false, //是否开启eslint
    devServer: {
        open: true, //是否自动弹出浏览器页面
        host: "localhost", 
        port: '8081', 
        https: false,   //是否使用https协议
        hotOnly: false, //是否开启热更新
        proxy: null,
    }
}

Vue3 解决跨域,内容只有第二步配置代理 和 Vue2 不一样,其余的一致。浏览器

devServer: {
    open: true, //是否自动弹出浏览器页面
    host: "localhost", 
    port: '8081',
    https: false,
    hotOnly: false, 
    proxy: {
        '/api': {
            target: 'https://www.v2ex.com/api', //API服务器的地址
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
}
相关文章
相关标签/搜索