js ajax跨域请求报错的解决办法

  在做项目时,遇到一个请求或着提交的错误,大概出现如下代码,原因是不能跨域请求。

No 'Access-Control-Allow-Origin' header ...等

  主要的解决方法有三个。


1.在后台更改header

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

    这个方法最简单有效,直接解决了问题。


2.使用JQuery提供的jsonp,需要将jQuery引入到vue项目中

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

3.使用http-proxy-middleware 代理解决(项目需要使用vue-cli脚手架搭建)

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

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

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/qq_34131399/article/details/79392437