国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue簡單封裝axios之解決post請求后端接收不到參數問題

2024-05-06 15:44:32
字體:
來源:轉載
供稿:網友

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

在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請求后端接收不到參數問題:    解決方案一:有效,但是兼容性不是很好,不是所有瀏覽器都支持      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中調用post請求方法:

<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請求方法

<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>

總結

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 孙吴县| 淄博市| 广安市| 海城市| 沁水县| 讷河市| 昭平县| 隆昌县| 迭部县| 九龙城区| 松潘县| 石景山区| 杭州市| 葵青区| 若尔盖县| 萨迦县| 花莲县| 铜梁县| 利津县| 瑞昌市| 徐州市| 全州县| 阿尔山市| 泸水县| 祁阳县| 株洲市| 平陆县| 桐庐县| 富平县| 大埔区| 林甸县| 湾仔区| 道孚县| 遂昌县| 怀化市| 泾川县| 淮安市| 大宁县| 滁州市| 延安市| 禹城市|