vue项目封装api接口

1. 服务端地址:http://xxx.xxx.xxx.xxx:8088

2. 本地项目地址:http://192.168.229.44:1234/demo/#/

1.当我们本机可以ping通xxx.xxx.xxx.xxx时,在地址栏输入http://xxx.xxx.xxx.xxx:8088/rcce/occu/list?pageNo=0&pageSize=5我们可以获得接口对应的数据,那么我们怎么样操作可以使得在地址栏中输入本机ip加上接口地址也能获得数据呢?答案是代理

配置好上面的代码后,我们可以实现在地址栏输入http://192.168.229.44:1234/rcce/occu/list?pageNo=0&pageSize=5我们一样可以获得数据

下面我们在项目中去使用axios调接口获得数据

 

上面的操作我们可以看出,每个接口如果我们都单独用axios去配置然后请求,这太麻烦了,url那么长,还带着ip,而且返回的数据还被data包裹了一层,以后如果所有请求要在请求头加个参数,还得全局搜索去修改,这太不便利了,所以我们选择封装一下。

 httpInterceptors.js文件内容就是一个拦截器,对接口进行统一处理。axios返回的数据,我们所需要的信息放在data.data里面,每次去拿都要点一下,不方便,有时候请求我们可能需要统一处理加个参数之类的。

 1 // request interceptor
 2 import { Message } from 'element-ui';
 3 
 4 export default service => {
    // 请求
5 service.interceptors.request.use( 6 config => { 7 // Do something before request is sent 8 if (!config.params) { 9 config.params = {}; 10 } 11 if (config.method === 'get') { 12 config.params.t = Date.now(); 13 } 14 return config; 15 }, 16 error => { 17 // Do something with request error 18 Promise.reject(error); 19 } 20 ); 21 // respone interceptor 22 service.interceptors.response.use( 23 response => { 24 const res = response.data; 25 if (res.code) { 26 Message({ 27 message: res, 28 type: 'error', 29 duration: 3 * 1000 30 }); 31 } else { 32 return response.data.data; 33 } 34 }, 35 error => { 36 Message({ 37 message: error, 38 type: 'error', 39 duration: 5 * 1000 40 }); 41 return Promise.reject(error); 42 } 43 ); 44 };

 services.js文件创建了一个公共的axios,后续的请求都通过这个。

import axios from '../../common/utils/http';
import httpInterceptors from './httpInterceptors';
import _ from 'lodash';
window.publishApiBath = location.origin + '/demo/rcce';// 公共路径
export const baseService = axios.create({
    baseURL: window.publishApiBath,
    paramsSerializer: (params) => {
        var parts = [];
        _.each(params, (val, key) => {
            if (val === null || typeof val === 'undefined') {
                return;
            }

            if (Array.isArray(val)) {

            } else {
                val = [val];
            }

            val.forEach((v) => {
                if (v instanceof Date) {
                    v = v.toISOString();
                } else if (typeof v === 'object') {
                    v = JSON.stringify(v);
                }
                parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(v));
            });
        });
        return parts.join('&');
    },
    timeout: 60000
});
httpInterceptors(baseService);

index.js创建了一个请求例子。

import { baseService } from './services';
export const getQualList = (pageNo, pageSize, qualName) => {
    return baseService({
        url: "/qual/list",
        method: 'get',
        params: {
            pageNo: pageNo - 1 || 0,
            pageSize,
            qualName
        },
    });
};

 

 

 

原文地址:https://www.cnblogs.com/grow-up-up/p/13085003.html