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