Vue简单封装axios—解决post请求后端接收不到参数问题
1.在src/下新建api文件夹,api/下新建index.js和public.js
在public.js中:
1 import axios from 'axios'; 2 import qs from 'qs' 3 import router from '../router' 4 import { MessageBox} from 'mint-ui' 5 6 // 注意点,按照以下写 7 var instance = axios.create(); 8 instance.defaults.timeout = 10000; 9 instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 10 11 export default { 12 fetchGet(url, params = {}) { 13 return new Promise((resolve, reject) => { 14 axios.get(url, params).then(res => { 15 if(res.data.code === 302) { 16 MessageBox('提示', '登录失效,请重新登录'); 17 MessageBox.alert('登录失效,请重新登录', '提示').then(action => { 18 router.push("/login"); 19 }); 20 } 21 resolve(res.data); 22 }).catch(error => { 23 reject(error); 24 }) 25 }) 26 }, 27 fetchPost(url, params = {}) { 28 /* 29 axios post请求后端接收不到参数问题: 30 31 解决方案一:有效,但是兼容性不是很好,不是所有浏览器都支持 32 let data = new URLSearchParams() 33 for (var key in params) { 34 data.append(key, params[key]) 35 } 36 */ 37 38 // 解决方案二:使用qs模块(axios中自带),使用qs.stringify()序列化params 39 return new Promise((resolve, reject) => { 40 axios.post(url, qs.stringify(params)).then(res => { 41 resolve(res.data); 42 }).catch(error => { 43 reject(error); 44 }) 45 }) 46 } 47 }
2.在index.js中:
1 import http from './public' 2 3 export const getStation = (params) => { 4 return http.fetchGet('/hydro/rest/getBelongUser', params); 5 } 6 7 export const userLogin = (params) => { 8 return http.fetchPost("/hydro/rest/login", params); 9 }
3.在Login.vue中调用post请求方法:
1 <template> 2 <div class="login"> 3 <h1>登录页面</h1> 4 <input type="text" placeholder="请输入用户名" v-model="Username"> 5 <input type="password" placeholder="请输入密码" v-model="Password"> 6 <input type="button" value="登录" @click="toLogin"> 7 </div> 8 </template> 9 10 <script> 11 import {userLogin} from "../../api/index" 12 13 export default { 14 name: 'app', 15 data() { 16 return { 17 Username: "", 18 Password: "" 19 } 20 }, 21 methods: { 22 toLogin() { 23 let params = { 24 username: this.Username, 25 password: this.Password 26 }; 27 28 userLogin(params).then(res => { 29 if(res.code === 200) { 30 this.$router.push("/home") 31 } 32 }) 33 } 34 } 35 } 36 </script>
4.在Home.vue调用get请求方法
1 <template> 2 <h1 class="home"> 3 {{stationName}} 4 </h1> 5 </template> 6 7 <script> 8 import {getStation} from "../../api/index" 9 10 export default { 11 data() { 12 return{ 13 stationName: "" 14 } 15 }, 16 created() { 17 getStation().then(res => { 18 this.stationName = res.msg; 19 }) 20 } 21 } 22 </script>
5.具体封装axios的demo地址:https://github.com/cry875258789/axios-demo