Vue的跨域问题解决

220 阅读1分钟

Vue的跨域问题

  1. 首先如果Vue项目下没有vue.config.js,就新建一个

    在其下的proxy配置项添加如下内容

    module.exports = {
        //解决路劲问题
        publicPath: './',
        devServer:{
            open:false,
            host:'0.0.0.0',
            port:8080,
            hot:true,
            proxy: {
                '/api': {
                  target:'http://localhost:8080/', // 你请求的第三方接口
                  changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
                  pathRewrite:{  // 路径重写,
                    '^/api': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.wpbom.com这个地址的时候直接写成/Api即可。
                  }
                }
            },  
        }
    }
    
    
  2. 在你的main.js下引入axios

    import Axios from 'axios'
    // 使用axios
    Vue.prototype.$axios=Axios
    //跨域
    Axios.defaults.baseURL = '/api'
    Axios.defaults.headers.post['Content-Type'] = 'application/json';
    
  3. 使用get或者post去请求跨域资源

    1. get方法

      axios.get('/user/findall')
                .then((response)=>{
                    this.indexdata=response.data
                })
                .catch((error)=>{
                    console.log(error);
                });
      
    2. post方法

      axios.post('/user/add',JSON.stringify(this.ruleForm))
                  .then(function () {
                    alert("成功")
                  })
                  .catch(function (error) {
                    console.log(error);
                  });