1、导语javascript
我发现好像我最近几回写文,都是在7号,很恰巧啊~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~前端
2、正文vue
最近用vue作一个订单管理混合开发APP,可是遇到个问题,使用了vueResource的post请求,后端作了跨域解决方案,但是前端仍是请求不出去,最后才发现,其实仍是有问题,其实踩到这个坑,根本缘由,是没把form data和request payload的区别搞懂,因此建议你们仍是找找资料,搞搞清楚java
一、浅谈 form data和request payload的区别json
get请求,是将请求参数以&方法,拼接在url后面,如:http://www.baidu.com?name=23&password=8888; segmentfault
真正能够明显看出区分的是在post请求上,后端
post请求时,头文件 中Content-Type 是默认值 application/x-www-form-urlencoded,参数是放在 form date中的,以下状况跨域
post请求时,头文件 中Content-Type 是默认值 application/json;charset=UTF-8,参数是放在 request payload 中的。服务器
顺便说下 Content-Type 的参数,你们能够参考:http://tool.oschina.net/commonsapp
二、解决vue-resource post请求跨域问题
vue提供了一个简单的解决方法,就是 Vue.http.options.emulateJSON = true; 其实等同于在headers中添加 'Content-Type': 'application/x-www-form-urlencoded'
不过,更稳妥的方法是如此写:
// 在路由的请求中如此设置 Vue.http.options.emulateJSON = true Vue.http.options.xhr = { withCredentials: true } Vue.http.options.crossOrigin = true Vue.http.options.emulateHTTP = true
Vue.http.options.root = URL.Purl // URL.Purl指的是服务器路径
为什么要如此写呢?感谢 我在寻找这问题时,看到的文章:https://segmentfault.com/a/1190000007087934
效果以下:
因此你们能够愉快的这么运行vue-resource了
getShopCartList() { this.$http.post(URL.ShopCartList, { openId: this.openId, userName: this.userName, accessToken: this.accessToken, sign: this.sign, shopId: this.shopId }).then( function (response) { this.$store.dispatch('update_loading', false) let status = response.body.status; if (status == 1) { let result = response.body.result; if (result !== null) { this.cartGoodLis = []; result.shopCarts.forEach((shopCartsItem) => { if (shopCartsItem.cartItems.length == 1) { this.cartGoodLis.push(shopCartsItem.cartItems[0]) } else { shopCartsItem.cartItems.forEach((shopCartsItems) => { this.cartGoodLis.push(shopCartsItems) }) } }); } else { this.cartGoodLis = []; } } else { // Router.verificationToUser(status, response.body.msg); } } ) }
3、 结尾
订单管理APP已经经过测试部的测试了,开心开心~~~~~~~~~~~~~~