一、通过new Service(apiList,config,request) 创建实力的方式批量创建出请求方法对象。
1.apiList 方法的json配置
2.config 主要配置baseUrl 其他我也还没搞明白源码是typeScript(哈哈哈)想要源码找我要
3.request 请求函数,接受一个promise对象的返回值 request的requestInfo参数有三个
const {url,config,mock} = requestInfo
二、安装方法和封装
npm install request-pre
import Service from 'request-pre';
import axios from 'axios';
import {stringify} from 'qs';
const formatContentType = function(contentType, data) {
const map = {
'application/x-www-form-urlencoded'(data) {
return stringify(data);
},
};
return map[contentType] && map[contentType](data) || data;
};
const requester = function(requestInfo) {
const {
url,
config,
mock
} = requestInfo;
// mock的处理
if (config['mock']) {
let data = [];
data = mock[config['mock']] ? mock[config['mock']] : [];
if (data['success']) {
return new Promise(function(resoult, reject) {
data.status = 200
resoult(data)
})
} else {
return new Promise(function(resoult, reject) {
data.status = 400
reject(data)
})
}
}
const {
path,
method,
body = {},
headers = {},
query = {}
} = url;
let baseURL = '';
if (config.baseURL) {
baseURL = config.baseURL;
}
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
const req = axios({
params: query,
baseURL,
method,
url: path,
data: formatContentType(headers['Content-Type'], body),
headers,
withCredentials: !baseURL,
});
return req.then((data) => data.data);
};
export const createService = function createService(apiSchemaList, serviceConfig) {
return new Service(apiSchemaList, serviceConfig, requester);
};
三、使用配置
//引入封装好的 createService构造函数
import { createService } from '/service';
var api= {
"loadList": {
"url": {
"path": "/getList",
"method": "get"
},
"mock": {
"success": true,
"data": {
"code": 200,
"data": []
}
},
"error": {
"success": false,
"data": {
"code": 400,
"data": []
}
}
},
"getDetail": {
"url": {
"path": "/getDetail",
"method": "get"
}
}
}
const service = createService(api, {
config: {
baseURL: 'http://59.111.90.154:7000/api/ingress',
},
});
export default service;
四、使用方法 详细使用方法请在node_modules中的request-pre中的tests中查看
axios中是通过params传递参数的,所以第二步就已经搞定了 参数传过去不变
//引入生成的api
import Service from './service'
Service.loadList({
config: {
mock: "success"
}
}).then(function(res){ })
Service.loadList({
query:{ a:1 }
}).then(function(res){ })