import axios from 'axios'; import qs from 'qs' import router from '../router' import { MessageBox} from 'mint-ui' // 注意點,按照如下寫 var instance = axios.create(); instance.defaults.timeout = 10000; instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; export default { fetchGet(url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, params).then(res => { if(res.data.code === 302) { MessageBox('提示', '登陸失效,請從新登陸'); MessageBox.alert('登陸失效,請從新登陸', '提示').then(action => { router.push("/login"); }); } resolve(res.data); }).catch(error => { reject(error); }) }) }, fetchPost(url, params = {}) { /* axios post請求後端接收不到參數問題: 解決方案一:有效,可是兼容性不是很好,不是全部瀏覽器都支持 let data = new URLSearchParams() for (var key in params) { data.append(key, params[key]) } */ // 解決方案二:使用qs模塊(axios中自帶),使用qs.stringify()序列化params return new Promise((resolve, reject) => { axios.post(url, qs.stringify(params)).then(res => { resolve(res.data); }).catch(error => { reject(error); }) }) } }
import http from './public' export const getStation = (params) => { return http.fetchGet('/hydro/rest/getBelongUser', params); } export const userLogin = (params) => { return http.fetchPost("/hydro/rest/login", params); }
<template> <div class="login"> <h1>登陸頁面</h1> <input type="text" placeholder="請輸入用戶名" v-model="Username"> <input type="password" placeholder="請輸入密碼" v-model="Password"> <input type="button" value="登陸" @click="toLogin"> </div> </template> <script> import {userLogin} from "../../api/index" export default { name: 'app', data() { return { Username: "", Password: "" } }, methods: { toLogin() { let params = { username: this.Username, password: this.Password }; userLogin(params).then(res => { if(res.code === 200) { this.$router.push("/home") } }) } } } </script>
#### 4.在Home.vue調用get請求方法vue
<template> <h1 class="home"> {{stationName}} </h1> </template> <script> import {getStation} from "../../api/index" export default { data() { return{ stationName: "" } }, created() { getStation().then(res => { this.stationName = res.msg; }) } } </script>