1.在src/下新建api文件夾,api/下新建index.js和public.js

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了雙灤免費建站歡迎大家使用!
在public.js中:
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請求后端接收不到參數(shù)問題:
解決方案一:有效,但是兼容性不是很好,不是所有瀏覽器都支持
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);
})
})
}
}2.在index.js中:
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);
}3.在Login.vue中調(diào)用post請求方法:
<template>
<div class="login">
<h2>登錄頁面</h2>
<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調(diào)用get請求方法
<template>
<h2 class="home">
{{stationName}}
</h2>
</template>
<script>
import {getStation} from "../../api/index"
export default {
data() {
return{
stationName: ""
}
},
created() {
getStation().then(res => {
this.stationName = res.msg;
})
}
}
</script>總結(jié)
以上所述是小編給大家介紹的Vue簡單封裝axios之解決post請求后端接收不到參數(shù)問題,希望對大家有所幫助!
本文名稱:Vue簡單封裝axios之解決post請求后端接收不到參數(shù)問題
網(wǎng)址分享:http://chinadenli.net/article10/jgpcdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、標(biāo)簽優(yōu)化、網(wǎng)站改版、響應(yīng)式網(wǎng)站、網(wǎng)站導(dǎo)航、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)