In the current front-end development, the front and back end separation development is more mainstream, so in the packaging method and modularization is also very need to master a skill. In fact, the following package is not very different from the axios package or AXIos package found on Baidu. The main thing is to add interceptors and simplify a little.

Install axios

npm install axios --save
Copy the code

Via mounted Axios (just for comparison)

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router"; / / routing
import store from "./store"; // Vuex
import axios from "axios";

Vue.config.productionTip = false;

Vue.prototype.$axios = axios;

new Vue({
	router,
	store,
	render: h= > h(App)
}).$mount("#app");
Copy the code

Use mounted Axios on the page

// post
this.$axios.post('products/list', { page: 1.page_size: 10 }).then(res= > {
    if (res.status == 200) {
        this.productsList = res.data;
    }
}).catch(err= > {
    console.log(err);
});
Copy the code

Through the encapsulated Axios

You also need to install QS (the QS plug-in can parse and serialize strings)

npm install qs
Copy the code

Then create an API folder under SRC, create a request.js file, and put the following code in it

import axios from 'axios';
import qs from 'qs';

// Create an axios instance
const service = axios.create({
    baseURL: 'http://127.0.0.1/api/'./ / API base_url
    // withCredentials: true, // Whether cookies are sent in cross-domain requests
    timeout: 5000 // Request timeout Settings
})

// Request interceptor
service.interceptors.request.use(config= > {
    // Do something before you request it?
    if(! config.data) { config.data = {}; }// console.log(config)
    // Set public parameters
    console.log(qs.stringify(config.data));

    return config;
}, error => {
    // Request processing error
    console.log(error); // For debugging
    return Promise.reject(error);
})

// Response interceptor
service.interceptors.response.use(response= > {
    // let res = respone.data; // If data.data is returned, return res
    return response;
}, error => {
    console.log('error:' + error); // For debugging
    return Promise.reject(error);
})

export default service;
Copy the code

Next, create an index.js file under the API folder (don’t create index.js if the API interface classification needs to be separated, such as login.js, user interface: user.js…).

import request from '@/api/request'; // Import wrapped Axios

/ / login
export function login (data) {
    return request({
        url: 'login'.method: 'post'.data: data
    })
}

// Product list
export function productsList () {
    return request({
        url: '/products/list'.method: 'get'})}Copy the code

Use wrapped AXIos on the page

import { Login } from '@/utils/helpers';
import { productsList } from '@/api'; {productsList, productsPoster}}

export default {
    data () {
        return {
            isLoading: true.productsList: []
        }
    },
    created () {
        this.init();
    }
    methods: {

        / / initialization
        init () {
            if(! Login()) { alert('Please log in');
                this.$router.go(- 1)
                return false;
            } else {
                this.getProductsList();
                this.isLoading = false; }},// Get the product list
        getProductsList () {

            // get
            productsList().then(res= > {
                if (res.status == 200) {
                    this.productsList = res.data;
                }
            }).catch(err= > {
                console.log(err);
            });

            // post
            productsList({ page: 1.page_size: 10 }).then(res= > {
                if (res.status == 200) {
                    this.productsList = res.data;
                }
            }).catch(err= > {
                console.log(err); }); }}}Copy the code

That’s all the content of this article wrapped in Axios, please leave a comment if you don’t understand, if you don’t write well, please leave a comment!!

conclusion

The benefit of the AXIos wrapper is the convenient management API, which I think is a good way to do it, and there is a uniform handling of the interceptor, if in every page to

this.$axios.get('/api/login').then(res => {});
Copy the code

When it comes time to modify, you have to go page by page, which will increase the workload (although this reason can be touched (^▽^)).

The original link: blog. Langting. Top/archives / 73…