註冊功能axios 與後臺介面的對接
阿新 • • 發佈:2018-11-07
axios 與後臺介面的對接
用的是前端框架vue,貼一段頁面程式碼 <table > <tr> <td >手機號:</td> <td ><input type="text" name="phone" v-model="phone" placeholder="請輸入手機號"></td> </tr> </table> 在template中input裡v-model一個雙向繫結資料 phone 。在vue中this.phone 獲取input的值, 再貼入我script中的程式碼
import axios from 'axios' import AppHead from '@/components/public/Head' import AppFoot from '@/components/public/foot' export default { name: 'rigist_', data(){ return{ phone:'', password:'', passwordC:'' } }, components: { 'app-head': AppHead, 'app-foot':AppFoot }, methods:{ //驗證使用者輸入資訊並且向後臺傳參 rigist(){ if(!this.phone|| !this.password || !this.passwordC) { alert("您有未填項,不能註冊") } else if(this.password != this.passwordC) { alert('兩次輸入的密碼不一致') } else { var rigistDate=this.$qs.stringify({ userPhoneNumber: this.phone, userPassword: this.password }); this.$axios.post( //相當於url?userPhoneNumber=1&userPassword=1 'http://192.168.0.109:8080/farmer/user/register#/',rigistDate, { headers:{"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",} }).then(function(response) { console.log(rigistDate.userPassword) this.$router.push({path:'/home'}) }) .catch(() => { this.loading = false }) } } } }
script中使用了一個qs類庫
功能是序列化。假設我要提交的資料如下
var a = {name:’hehe’,age:10};
qs.stringify序列化結果如下
name=hehe&age=10
第一次與後臺互動各種報錯,403之類的總之報的最多的是傳輸媒體型別錯誤,與後臺的資料型別不匹配,因為我註冊得傳輸post型別所以在前面var一個rigistDate裡封裝了phone和password
var rigistDate=this.$qs.stringify({ userPhoneNumber: this.phone, userPassword: this.password });
接下來就要做的是從後臺返回的massage 提示註冊成功 失敗然後跳轉其他頁面