在vue項目中使用axios發送FormData


這個是axios的中文文檔,挺詳細的:

https://www.kancloud.cn/luponu/axios/873153

 

文檔中的    使用 application/x-www-form-urlencoded format    這一部分講的就是  通過axios發送 FromData 的方法,

 

下面是我在vue項目中使用的示例:

在本組件的method添加了一個點擊事件,點擊了發送 FromData 格式的 post請求。

 

<template>
    <div class="login">

      <div>
        <div class="login_input"><input type="text" v-model="tel" placeholder="請輸入手機號" autocomplete="false"><button class="auth-code-btn" @click="getAuthCode">獲取驗證碼</button></div>


        <div class="login_input"><input type="text" v-model="msg" placeholder="請輸入驗證碼" autocomplete="false"></div>
      </div>
      <div class="login_btn" @click.stop="login">登錄</div>
    </div>


</template>

<script>
    import Header from '../components/Header';

    /*
    我們想通過axios 提交FromData,需要用到qs庫(這個庫不用npm下載,直接引用即可),
    qs是一個url參數轉化(parse和stringify)的js庫。
    qs.stringify() 和JSON.stringify() 作用相似,都是序列化,但他們完全不是一個東西,
    假設我要提交的數據是:  let a = {name:'hehe',age:10};
    qs.stringify(a)序列化結果為  name=hehe&age=10
    而JSON.stringify序列化結果為: {"name":"hehe","age":10}  轉成字符串

    使用 application/x-www-form-urlencoded format 使用這種請求頭 發送法數據就是 FromData格式
    默認情況下,axios將JavaScript對象序列化為JSON。 要以application / x-www-form-urlencoded格式發送數據,您可以使用以下選項之一。
    這里我們是采用的ES6 語法 引入 的qs模塊
    */
    import qs from 'qs';

    export default {
        name: "Login",
        components: {Header},
        data(){
          return {
            tel: '',
            msg: ''
          }
        },


        methods: {


          //獲取驗證碼
          async getAuthCode(){
            // console.log('sss');
            // let data = await this.$http.post('https://i.meituan.com/account/custom/mobilelogincode2' + '?mobile=17664068406');
            //直接post請求及傳參數
            // let data = await this.$http.post('https://i.meituan.com/account/custom/mobilelogincode2', { mobile: '17664068406'});
            // console.log(data);

            //通過POST方式發送FormData格式的參數 的寫法  
            let data = await this.$http({//這里的 this.$http 就是axios 因為 我在vue原型上,掛載axios的時候,把axios改名為$http 了。
              url: 'https://i.meituan.com/account/custom/mobilelogincode2',  //請求路徑(接口)
              method: 'POST', //請求方式
              headers: { 'content-type': 'application/x-www-form-urlencoded' }, // 請求頭,發送FormData格式的數據,必須是 這種請求頭。
              data: qs.stringify({mobile: '17664068406'}),  //發送請求要傳的FormData參數。必須用 qs.stringify()序列化一下。
            });

            console.log(data);



          }




        }



    }

 

上面的this.$http 就是axios 因為 我在vue原型上,掛載axios的時候,把axios改名為$http 了。 我掛載的方法,可以看  https://www.cnblogs.com/taohuaya/p/10177967.html 這篇博客,有一個地方提到了。

 

下面我們看一下效果:

請求時發送的信息:

 

 返回的數據:

 

 

 

 

 搞定了,結束。

 


免責聲明!

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



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