欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue项目中跨域问题解决方案

程序员文章站 2022-11-15 11:22:22
方法 后台更改header 使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建) jquery jsonp...

方法

  • 后台更改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(',') 
   } 
  }) 
 } 
}

总结

以上所述是小编给大家介绍的vue项目中跨域问题解决方案,希望对大家有所帮助