vue跨域解决方法

vue项目中,前端与后台进行数据请求或者提交的时候,如果后台没有设置跨域,前端本地调试代码的时候就会报“No 'Access-Control-Allow-Origin' header is present on the requested resource.” 这种跨域错误。

要想本地正常的调试,解决的办法有三个:

一、后台更改header

1
2
header('Access-Control-Allow-Origin:*');//允许所有来源访问 
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式   

这样就可以跨域请求数据了。

二、使用JQuery提供的jsonp  (注:vue中引入jquery,自行百度)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
methods: { 
   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(',') 
      
     }) 
  

  

通过这种方法也可以解决跨域的问题。

 

三、使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)

 

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

1、打开config/index.js,在proxyTable中添写如下代码:

     

1
2
3
4
5
6
7
8
9
proxyTable: { 
   '/api': {  //使用"/api"来代替"http://f.apiplus.c" 
     target: 'http://f.apiplus.cn', //源地址 
     changeOrigin: true, //改变源 
     pathRewrite: { 
       '^/api': 'http://f.apiplus.cn' //路径重写 
      
  
}

2、使用axios请求数据时直接使用“/api”:

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

通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下:

1
2
3
4
5
let serverUrl = '/api/'  //本地调试时 
// let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 
export default { 
   dataUrl: serverUrl + 'bj11x5.json' 
} vue项目中,前端与后台进行数据请求或者提交的时候,如果后台没有设置跨域,前端本地调试代码的时候就会报“No 'Access-Control-Allow-Origin' header is present on the requested resource.” 这种跨域错误。

要想本地正常的调试,解决的办法有三个:

一、后台更改header

1
2
header('Access-Control-Allow-Origin:*');//允许所有来源访问 
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式   

这样就可以跨域请求数据了。

二、使用JQuery提供的jsonp  (注:vue中引入jquery,自行百度)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
methods: { 
   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(',') 
      
     }) 
  

  

通过这种方法也可以解决跨域的问题。

 

三、使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)

 

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

1、打开config/index.js,在proxyTable中添写如下代码:

     

1
2
3
4
5
6
7
8
9
proxyTable: { 
   '/api': {  //使用"/api"来代替"http://f.apiplus.c" 
     target: 'http://f.apiplus.cn', //源地址 
     changeOrigin: true, //改变源 
     pathRewrite: { 
       '^/api': 'http://f.apiplus.cn' //路径重写 
      
  
}

2、使用axios请求数据时直接使用“/api”:

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

通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下:

1
2
3
4
5
let serverUrl = '/api/'  //本地调试时 
// let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 
export default { 
   dataUrl: serverUrl + 'bj11x5.json' 
}

猜你喜欢

转载自blog.csdn.net/qq_40963664/article/details/79976169