vue $http的get和post请求跨域问题解决
首先在config/index.js中配置proxyTableproxyTable: {'/api':{// target:'http://jsonplaceholder.typicode.com',target:'http://localhost:9080',changeOrigin:true,...
·
首先在config/index.js中配置proxyTable
proxyTable: {
'/api':{
// target:'http://jsonplaceholder.typicode.com',
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("服务器异常");
});
}
}
值得注意的是:
- 一定要设置 {emulateJSON: true},不然跨域不成功.
- 跨域在chrome浏览器中你看到的还是http://localhost:8080(即你启动vue的地址,而不是你服务器应用的地址),所以你看到不要惊讶,其实是跨域成功的。
- http请求中要带上/api,经过index.js的代理会将/api去掉,浏览器中的访问地址为http://localhost:8080/api/amdatashift/login/user,然后实际的访问的地址是http://localhost:9080/amdatashift/login/user。通过代理就实现了跨域访问。
更多推荐
已为社区贡献6条内容
所有评论(0)