• Vue简单封装axios—解决post请求后端接收不到参数问题


    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>
  • 相关阅读:
    emacs写cnblog博客
    emacs写cnblog博客
    linux安装jdk
    linux远程服务器启动mysql时显示:/tmp/mysql.sock 不存在的解决方法
    最新Linux系统下安装MySql 5.7.17全过程及注意事项
    Xshell实现Windows上传文件到Linux主机
    4种java定时器
    微信的redirect_uri参数错误解决办法
    要善于借势破局——宁向东的清华管理学课第4课
    Java内存区域
  • 原文地址:https://www.cnblogs.com/mica/p/10879770.html
Copyright © 2020-2023  润新知