Vue-CLI3.0 project construction process Series IV: axios application in the project

Keywords: axios network Vue

Now let's talk about the request method in the project - axios

Insert (from netizen): storage token suggests state+localStorage
Because state is a single page, you don't need to log in to open the second web page for the same browser, so you need to use cookies or localstorage. Why not use cookies: 1, the amount of cookie storage is small; 2, the number of cookies is limited; 3, in fact, the most important request will bring cookies, increasing the network burden, so it is recommended to use state+localStorage, of course, to deal with it Good encryption, expiration and other issues

Create index.js file under api folder to make general configuration of axios

import axios from 'axios'
import router from '../router/index'
import qs from 'qs'

// Create axios instance
const service = axios.create({
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
    // Transform the data according to the needs: for example, if the token value needs to be added uniformly, the following processing can be done
    if (!config.params) {
        config.params = {}
    }
    config.params.accessToken = localStorage.getItem('accessToken')
    if (config.method === 'post') {
        config.data = qs.stringify(config.data)
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    return config
}, error => {
    Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(response => {
    // Process the returned data as required: process according to the front end and back end conventions (such as the processing that the user requests to return when he / she is not logged in or the permission expires)
    const res = response.data
    if (!res || res.code === -1) {
        // Jump to login page after permission expires
        window.location.href = '' // Landing page link
    }
    return response
}, error => {
    if (!error || !error.response) {
        // Jump 500
        router.replace({
            path: '/500'
        })
    }
    // Check state
    switch (error.response.status) {
        case 402:
            // Clear token information
            alert('Login expired, please login again')
            // Clear token information
            localStorage.setItem('accessToken', '')
            // permissionUtil.logout()

            return error
        case 404:
            // Jump 404
            router.replace({
                path: '/404'
            })
            break
    }
    return Promise.reject(error)
})

export default service

Create a new constant file in the api folder to define all the interfaces needed in the project

// Define the joint commissioning interface address in the development phase
const BASE_1 = ''

const env = process.env.NODE_ENV
let BASE
if (env === 'production') { // Production environment is officially packaged
    BASE = window.myConfig.baseUrl // Online interface address
} else if (env === 'development') { // Development environment local test use
    BASE = BASE_1
}

// Define required interfaces
const constant = {
    /*demo Module interface*/
    demo: BASE + 'https://api.apiopen.top/EmailSearch?number=1012002', // demo interface
}

export default constant

Create a new demo.js file under the api folder. This is an example file - in the project, we can write request methods in modules. Each module has a JS file to put its interface method in, so centralized management looks more organized (I like this writing method personally).

import axios from './index'
import constant from './constant'

/**
 * demo Interface call get
 * @param param Keyword
 */
export function getDemo1(param) {
    return axios({
        url: constant.demo,
        method: 'get',
        params: param
    })
}

/**
 * demo Interface call post
 * @param param Keyword
 */
export function getDemo2(param) {
    return axios.post(constant.demo, param)
}

Create a new demo folder under the view folder - create a new index.vue file, and write an example of using the request method

<template>
    
</template>

<script>
    import { getDemo1 } from "../../api/demo"

    export default {
        name: "index",
        data() {
            return {
            }
        },
        methods: {
            // demo method
            getDemo() {
                const that = this
                let param = {
                    data: 'test'
                }
                getDemo1(param).then((res) => {
                    if (res.data.code === 0) {
                        // Success
                    } else {
                        // fail
                        this.$message.error(res.data.msg)
                        return
                    }
                })
            }
        }
    }
</script>

<style scoped>

</style>

 

Posted by rortelli on Tue, 22 Oct 2019 09:59:20 -0700