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(',') 
      } 
    }) 
  } 
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM