vue project access mock & Axios general configuration

Keywords: Javascript axios Vue JSON mockjs

Preface

Similarly, in the process of project development, there are often no interfaces and the front-end pages have been built. At this time, in order to improve the efficiency of front-end development and liberate productivity, we FE can do some interface simulation according to the pre-defined interface documents, and so on. After the back-end partners develop the interface, we only need to replace an interface base address.

Initial preparation

Here we have taken the vue project as an example. The required modules are: mockjs, express; direct npm installation can be done.

1.Mock.js  // Used to quickly construct random data http://mockjs.com/examples.html 
2.express // Used to quickly build the local service http://expressjs.jser.us/

Use in projects

Usually a mock folder will be built in the vue project, which contains the corresponding processing files:

Interface Distribution Module

It's mainly about distributing the request URL s from the front end and starting local services.

let Mock = require('mockjs');
let express = require('express');
let app = express();

let bodyParser = require('body-parser'); // Parsing post requests

// mock data related api
let homeAPI = require('./home');
let specialAPI = require('./special');
let appAPI = require('./app');

app.use(bodyParser.json());

// Set cross domain
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    // Configuration here is based on the request header carried by the front-end request
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
    next();
});

// 1. Home page interface: post
app.post('/android/home', (req, res) => {
    // Analog timeout
    // setTimeout(() => {
    //     res.json(Mock.mock(homeAPI.getHome(req)));
    // }, 12000);
    res.json(Mock.mock(homeAPI.getHome(req)));
    console.log('Successful request for home page data...');
})

// 2. Thematic interface: post
app.post('/android/special/list', (req, res) => {
    res.json(Mock.mock(specialAPI.getSpecialList(req)))
    console.log('Request topic list data succeeded...');
})
app.post('/android/special/detail', (req, res) => {
    res.json(Mock.mock(specialAPI.getSpecialDetail(req)))
    console.log('Successful request for thematic details data...');
})

// 3.APP Application Interface: post
app.post('/android/special/app', (req, res) => {
    res.json(Mock.mock(appAPI.getAppList(req)))
    console.log('request app Successful list data...');
})

app.listen('3000', () => {
    console.log('mock Server startup ing in... port: 3000')
})

Interface Data Module

As an example of the specialApi above, this is the module used to process the xxx/special/list interface.

let Mock = require('mockjs');
let Random = Mock.Random;
// Thematic module
// 1. List of topics
let specialList = [];
let total = 100;
// Prepare 100 topic list data
for (let index = 0; index < total; index++) {
    specialList.push(
        Mock.mock({
            id: '@increment',
            title: '@ctitle',
            desc: '<p>'+Random.cparagraph()+'</p>',
            icon: 'photo/special/1380/special_1380.jpg',
            view_count: '@natural(60, 1000)',
            comment_count: '@natural(60, 100)',
            save_money: '@float(10, 50, 2, 2)',
            app_count: '@natural(10, 100)',
            detail_icon: 'https://images.tutuapp.com/photo/special/000/001/' + '@natural(100, 200)' + '/414x155.jpg',
        })
    );
}

module.exports = {
// List data return
    getSpecialList: config => {
        // Parameter parsing
        console.log(config.body);
        let { page = 1, size, lang, order_by } = config.body;
        let tempList = [];
        let pageList;
        // Sort type
        tempList = order_by === 'view' ? specialList.reverse() : specialList;
        // Paging processing
        pageList = tempList.filter((item, index) => index < page * size && index >= (page-1)*size);
        // Return the result of the processing. No exception status code processing is done here.
        return {
            status: {
                code: 0,
                message: 'Request successful',
                time: '2019-07-03 16:45:12',
            },
            data: pageList,
        };
    },
// List Details Data Return
    getSpecialDetail: config => {
        let { id, page = 1, size, lang } = config.body;
        return {
            status: {
                code: 0,
                message: 'Request successful',
                time: '2019-07-03 16:45:12',
            },
            data: {
                detail: specialList[Math.ceil(1 + Math.random() * 98)],
                total: Math.ceil(Math.random() * 100),
            },
        };
    },
};

Start local services

Here we need to create a new line of commands under the script field of the package.json file to start the server.

    "mock": "node src/mock/index.js"
    The service can be opened by executing npm run mock under the terminal, and then we can safely request data.

axios Universal Configuration

1. Create axios instances

// 1. Introduce required dependencies: axios,Vue,store,router, tool function toast, etc.
import axios from 'axios';
import Vue from 'vue';

// Create axios instances
const Axios = axios.create({
    // Adding Initialization Configuration
    baseURL: process.env.BASE_API, // Base address
    timeout: 10000, // overtime
    // withCredentials: true, // send cookies when cross-domain requests
});

// const TOKEN = window.sessionStorage.getItem('token'); // when set token

// request interceptor
Axios.interceptors.request.use(
    config => {
        // TODO: Add request header processing logic, such as adding token; you can also set up the open request loading animation
        // config.headers['X-Token'] = TOKEN
        return config;
    },
    error => {
        console.log('request error:', error); // for debug
        return Promise.reject(error);
    }
);

/**
 * Unified treatment in two ways
 * 1.Processing by http status code status: response. status and error.response.status
 * 2.Through the custom status code in response.data: response.data. code processing (exception handling directly in the first callback reprocessing)
 */

// Response interceptor
Axios.interceptors.response.use(
    response => {
        const res = response.data;
        // 1. Unified Processing by Custom code
        // 2. It can also be processed by response.status === 200; 1 is used here.
        if (res.status.code === 0) {
            return res.data; // Success
        } else {
            // for example: Exceptional code for custom processing
            if (res.status.code === 50008 || res.status.code === 50012) {
                // Tost processing or jumping with some hints
                alert('Erroneous!!!');
            }
            return Promise.reject(new Error(res.status.message || 'Error'));
        }
        
    },
    error => {
        // Response error handling: such as timeout, disconnection, permission, etc.
        console.log('response error:', error); // No status code display under local development for debug
        console.log(error.response); // for debug
        // const res = error.response;
        // if (res) {
        //     // The request has been issued, but not in the 2xx range
        //     errorHandle(response.status, response.data.message);
        //     return Promise.reject(res);
        // } else {
        //     // Handle disconnection or timeout.
        //     // Network state can control the display and hiding of a global disconnection prompt component in app.vue
        //     if (!window.navigator.onLine) {
        //         console.log('disconnected...');
        //     } else {
        //         return Promise.reject(error);
        //     }
        // }
    }
);

/**
 * Unified Error Handling after Failure of Request
 * @param {Number} status Status code for request failure
 */
const errorHandle = (status, tips) => {
    // State Code Judgment
    switch (status) {
        //     // 401: Unlogged, jump to logon page
        //     case 401:
        //         toLogin();
        //         break;
        //     // 403 token expires
        //     // Clear token and jump to the login page
        //     case 403:
        //         tip('Log in expired, please log in again');
        //         localStorage.removeItem('token');
        //         store.commit('loginSuccess', null);
        //         setTimeout(() => {
        //             toLogin();
        //         }, 1000);
        //         break;
        // 404 request does not exist
        case 404:
            console.log('The requested resource does not exist');
            break;
        default:
            console.log(tips);
    }
};

// Implementing plug-ins, exposing install methods, which can be used for vue instances
// Request via this.$http.post or get
export const http = {
    install(Vue) {
        Vue.prototype.$http = Axios;
    }
}

// Export an Axios instance
export default Axios

2. use

1.Use through plug-ins, stay mian.js Import
    import { http } from './api/http';
    Vue.use(http);
    //Request through this.$http.post | get in the component instance
    
2.Extract the request method, Introduce the above derived Axios Example
    import request from './http';

    // Home page request
    export function getHomeData(data) {
        return request({
            url: '/home',
            method: 'post',
            data
        })
    }
            
            


Posted by reagent on Thu, 10 Oct 2019 12:02:02 -0700