vue $http的get和post(开发环境)请求跨域问题解决
this.$http.get('/api/Login/GetPackageInfo',
{
params: {
'packageId': this.editModel.packageId,
'stationNum': this.userInfo.position,
'worker': this.userInfo.worker,
'isNewDB': this.$store.state.isNewDB
}
},
{emulateJSON: true}
).then(function (data) {
var obj = JSON.parse(data.body);
});
本文链接:https://blog.csdn.net/weixin_38070406/article/details/81294812
首先在config/index.js中配置proxyTable
proxyTable: {
'/api':{
target:'http://localhost:9080',
changeOrigin:true,
pathRewrite:{
'/api':''
}
}
用户名和密码登录的表单提交
methods: {
// get请求
// submitForm() {
// var formData=JSON.stringify(this.ruleForm);
// this.$http.get('/api/amdatashift/login/probe').then(function(data){
// }).catch(function(){
// console.log("服务器异常");
// });
// }
//post请求
submitForm() {
var formData=JSON.stringify(this.ruleForm);
this.$http.post('/api/amdatashift/login/user',{
username:this.ruleForm.username,
password:this.ruleForm.password
},{emulateJSON:true})
.then(function(data){
console.log(data);
}).catch(function(){
console.log("服务器异常");
});
}
}
值得注意的是:
- 跨域在chrome浏览器中你看到的还是http://localhost:8080(即你启动vue的地址,而不是你服务器应用的地址),所以你看到不要惊讶,其实是跨域成功的。
- http请求中要带上/api,经过index.js的代理会将/api去掉,浏览器中的访问地址为http://localhost:8080/api/amdatashift/login/user,然后实际的访问的地址是http://localhost:9080/amdatashift/login/user。通过代理就实现了跨域访问。