index.js
2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var http = require('http'),
conf = require("./conf");
var request = require('request');
var express = require('express');
var app = express();
var bodyParser = require('body-parser'); //body序列化插件
app.use(bodyParser.urlencoded({extended: false}));
var SERVICE_URL = "/service.api.yohobuy.com";//新服务的URL
app.get('/test',function(req,res,next){
res.send('hi~~~');
});
/**
* 路由生成
*/
function route() {
for(var i=0;i<conf.apis.length;i++) {
var api = conf.apis[i];
for(var j=0;j<api.methods.length;j++){
if(api.route === SERVICE_URL) {
api.route += '/*';
}
console.log('method: ['+api.methods[j]+'] route:'+api.route);
app[api.methods[j]](api.route, function(req, res, next) {
var form = req.body?req.body:{};
var url = whiteProc('http:/'+req.url,form,req.query);
console.log('call method:'+req.method+' url:'+url);
procRes(req.method,url,req.body,res);
});
}
}
}
/**
* 白名单处理
* @param {[type]} url [description]
* @param {[type]} form [description]
* @param {[query]} query [description]
* @return {[type]} [description]
*/
function whiteProc(url,form,query) {
var list = conf.whiteList;
var method = query.method?query.method:form['method'];
method = method?method:'';
for(var i=0;i<list.length;i++) {
if(url.indexOf(list[i].api)>-1||method === list[i].api) {
console.log('match api:'+list[i].api+' map:'+ list[i].map);
return list[i].map;
}
}
console.log('no match url:'+url);
return url;
}
/**
* 处理代理参数
* @param {string} method 方法
* @param {string} url 代理地址
* @param {Object} form 表单数据
* @param {Object} res 响应信息
* @return {void}
*/
function procRes(method,url,form, ress) {
if(method === "GET") {
request(url,callback);
} else {
request.post({url:url, form: form},callback);
}
function callback(err,res,body){
if (!err && res.statusCode == 200) {
ress.send(body);
}
else {
if(res) {
console.log('errorCode:'+res.statusCode);
}
console.log(err);
ress.send(body);
}
}
}
console.log('app start!');
route();
app.listen(3000);