VUE解决跨域问题

225 阅读1分钟

什么是跨域? 浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 域名:  主域名不同 www.baidu.com/index.html -->www.sina.com/test.js  子域名不同 www.666.baidu.com/index.html -->www.555.baidu.com/test.js  域名和域名ip www.baidu.com/index.html -->http://180.149.132.47/test.js 端口:  www.baidu.com:8080/index.html–… www.baidu.com:8081/test.js 协议:  www.baidu.com:8080/index.html–… www.baidu.com:8080/test.js 备注:  1、端口和协议的不同,只能通过后台来解决  2、localhost和127.0.0.1虽然都指向本机,但也属于跨域

  getData () { 
    var self = this 
    $.ajax({ 
      url: 'http://f.apiplus.cn/bj11x5.json', 
      type: 'GET', 
      dataType: 'JSONP', 
      success: function (res) { 
        self.data = res.data.slice(0, 3) 
        self.opencode = res.data[0].opencode.split(',') 
      } 
    }) 
  } 
} 
方法3.使用http-proxy-middleware 代理解决(项目使用[vue](https://so.csdn.net/so/search?q=vue&spm=1001.2101.3001.7020)-cli脚手架搭建)

例如请求的url:“http://f.apiplus.cn/bj11x5.json”

```proxyTable: { 
  '/api': {  //使用"/api"来代替"http://f.apiplus.c" 
    target: 'http://f.apiplus.cn', //源地址 
    changeOrigin: true, //改变源 
    pathRewrite: { 
      '^/api': 'http://f.apiplus.cn' //路径重写 
      } 
  } 
}

或者使用axios请求数据时直接使用“/api”:

getData () { 
 axios.get('/api/bj11x5.json', function (res) { 
   console.log(res) 
 })

在根目录下新建vue.config.js文件夹

    // baserUrl:'/',    //配置根目录
    outputDir:'dist',   //构建输出
    assetsDir:'assets',     //静态资源目录
    lintOnSave:false,   //是否开启eslint保存检测
    devServer:{
        open:true,      //启动项目之后不会立即运行
        host:'localhost',   //主机名称
        // port:8080,      //端口号,默认就是8080
        https:false,
        hotOnly:false,      //热更新
        proxy:{
            '/api':{
                target:'http://192.168.2.170',
                ws:true,
                changeOrigin:true,  //可跨域
                pathRewrite:{
                    '^/api':''
                }
            }
        }
    }
}