本文给大家介绍了vue项目中跨域问题的完美解决方案,通过更改header,使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
方法
- 后台更改header
- 使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
- Jquery jsonp
后台更改header
1 2 | header( 'Access-Control-Allow-Origin:*' );
header( 'Access-Control-Allow-Method:POST,GET' );
|
使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
打开config/index.js,在proxyTable中添写如下代码:
1 2 3 4 5 6 7 8 9 | proxyTable: {
'/api' : {
target: '填写请求源地址' ,
changeOrigin: true ,
pathRewrite: {
'^/api' : ''
}
}
}
|
使用axios
1 2 3 4 5 | this .$axios.post( "/api/地址" ,{
发送的数据
}).then(data=>{
console.log(data);
})
|
axios的配置(main.js)
1 2 | axios.defaults.headers.post[ "Content-type" ]= "application/json" ;
Vue.prototype.$axios=axios;
|
使用ES6fetch请求
1 2 3 4 5 6 7 8 9 10 11 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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( ',' )
}
})
}
}
|