欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue简易Http请求

程序员文章站 2022-05-06 21:53:30
####http.js 工具类import axios from 'axios';axios.defaults.baseURL = "http://localhost:8090/";axios.defaults.responseType = 'json';axios.defaults.timeout = 200000;//getconst get = (url, params) => { return axios({ method: 'get',...

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

结果:
vue简易Http请求

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