vue初級學習--使用 vue-resource 請求數據


一、導語

  我發現好像我最近幾次寫文,都是在7號,很恰巧啊~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

二、正文

  最近用vue做一個訂單管理混合開發APP,但是遇到個問題,使用了vueResource的post請求,后端做了跨域解決方案,可是前端還是請求不出去,最后才發現,其實還是有問題,其實踩到這個坑,根本原因,是沒把form data和request payload的區別搞懂,所以建議大家還是找找資料,搞搞清楚

  1、淺談 form data和request payload的區別

 

  • form date  

  get請求,是將請求參數以&方法,拼接在url后面,如:http://www.baidu.com?name=23&password=8888;   

 

  真正可以明顯看出區分的是在post請求上,

  post請求時,頭文件 中Content-Type 是默認值  application/x-www-form-urlencoded,參數是放在 form date中的,如下情況

  

  • request payload

    post請求時,頭文件 中Content-Type 是默認值  application/json;charset=UTF-8,參數是放在 request payload 中的。

    順便說下 Content-Type 的參數,大家可以參考:http://tool.oschina.net/commons

  2、解決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);
            }
          }
        )
      }

 三、 結尾

訂單管理APP已經通過測試部的測試了,開心開心~~~~~~~~~~~~~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM