Vue项目中跨域问题解决

Vue跨域解决方案
本文介绍了解决Vue项目中跨域问题的多种方法,包括后台更改header设置、使用http-proxy-middleware代理、通过Jquery实现jsonp请求等。每种方法都提供了具体的实现步骤。

Vue项目中跨域问题解决

方法

  • 后台更改header
  • 使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
  • Jquery jsonp

后台更改header

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

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

打开config/index.js,在proxyTable中添写如下代码:
proxyTable: { 
  '/api': { 
    target: '填写请求源地址', //源地址 
    changeOrigin: true, //是否跨域
    pathRewrite: { 
      '^/api': '' //路径重写 
      } 
  } 
}
使用axios
 this.$axios.post("/api/地址",{
     发送的数据
    }).then(data=>{
      console.log(data);
    })
axios的配置(main.js)
axios.defaults.headers.post["Content-type"]="application/json";
Vue.prototype.$axios=axios;
使用ES6fetch请求
fetch("/api/test/testToken.php",{
      method:"post",
      headers:{
        "Content-type":"application/json",
      },
      body:JSON.stringify({发送数据})
    }).then(result=>{
      return result.json()
    }).then(data=>{
      console.log(data);
    })

使用jquery jsonp

methods: { 
  getData () { 
    var self = this 
    $.ajax({ 
      url: '地址', 
      type: 'GET', 
      dataType: 'JSONP', 
      success: function (res) { 
        self.data = res.data.slice(0, 3)
        self.opencode = res.data[0].opencode.split(',') 
      } 
    }) 
  } 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值