vue简易Http请求

2022-08-08,,,

####http.js 工具类

路由的细节就不说了,直接看代码吧

import axios from 'axios';

axios.defaults.baseURL = "http://localhost:8090/";
axios.defaults.responseType = 'json';
axios.defaults.timeout = 200000;
//get
const get = (url, params) => {
    return axios({
        method: 'get',
        withCredentials: true,
        url,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            timestamp: getNow(new Date()),
            apiCode: url,
            apiVersion: '1.0.0',
        },
        params,
        data: undefined,
    });
};

//post
const post = (url, data) => {
    console.log('url:' + url);
    console.log('data:' + JSON.stringify(data));
    if (!data) {
        data = {};
    }
    data = JSON.stringify(data);
    return axios({
        method: 'post',
        withCredentials: true,
        url,
        responseType: 'text',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',

            timestamp: getNow(new Date()),
            apiCode: url,
            apiVersion: '1.0.0',
        },
        transformResponse: [
            function(data) {
                return JSON.parse(data);
            },
        ],
        pararms: undefined,
        data: data || {},
    });
};
const getNow = now => {
    return (
        now.getFullYear() +
        fillDate(now.getMonth()) +
        fillDate(now.getDate()) +
        fillDate(now.getHours()) +
        fillDate(now.getMinutes()) +
        fillDate(now.getSeconds())
    );
};
const fillDate = str => {
    if (('' + str).length == 1) {
        str = '0' + str;
    }
    return ('' + str).length == 1 ? '0' + str : str;
};
export default { get, post };

#####调用:

<template>
    <button @click="testClick">test</button>
</template>

<script>
    export default {
        name: 'HelloWorld',
        props: {
            // msg: String
        },

        data() {
            return {
                test: ''
            }
        },

        methods: {
            testClick() {
                //调用后台接口
                this.$http
                    .get('/user/queryUser')
                    .then(res => {
                        console.log(res);
                    })
                    .catch(function() {

                    });
            }
        }
    }
</script>


<style scoped>

</style>

结果:

本文地址:https://blog.csdn.net/qq_42919520/article/details/107161918

《vue简易Http请求.doc》

下载本文的Word格式文档,以方便收藏与打印。