proxy.js
2.3 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
99
100
101
102
103
'use strict';
const Controller = require('egg').Controller;
class ProxyController extends Controller {
async info() {
const { ctx } = this;
ctx.body = {
name: `hello ${ctx.params.id}`,
};
}
getOptions() {
const { ctx, config } = this;
const { url, type } = ctx;
let catalog = url.substring(1, url.indexOf('/', 1));
let pathUrl = url.substring(url.indexOf('/', 1));
let fullPath = '/' + catalog + config.restful.version + pathUrl;
return {
'host': config.restful.host, //后台请求地址
'port': config.restful.port,
'path': fullPath,
'method': type,
'agent': false,
'headers': {
"Accept": "application/json",
"Content-Type": "application/json",
'User-Agent': 'Request for Express'
}
};
}
addToken(options) {
const { ctx } = this;
if (ctx.session.passport && ctx.session.passport.user && ctx.session.passport.user && ctx.session.passport.user.token) {
options.headers['Authorization'] = "Bearer " + ctx.session.passport.user.token;
}
if (ctx.headers['device-id']) {
options.headers['Device-Id'] = ctx.headers['device-id'];
}
if (ctx.ip) {
options.headers['Client-Ip'] = ctx.ip;
}
return options;
}
splitUrl(fullUrl) {
const { config } = this;
if (config.prefix && config.prefix.length > 1) {
fullUrl = fullUrl.substring(config.prefix.length - 1);
}
return fullUrl.substring(4);
}
async get() {
const { ctx, config, logger } = this;
const { originalUrl } = ctx;
const { restful = {} } = config;
const { host } = restful;
const { access_token } = ctx.session.user_info;
const url = originalUrl.substring(4);
const result = await ctx.curl(`${host}${url}`, {
method: 'GET',
dataType: 'json',
headers: {
'authorization': `Bearer ${access_token}`,
'accept': 'application/json',
'content-type': 'application/json'
},
timeout: [5000, 60000]
});
logger.info(
"proxy url:",
`${host}${url}`,
'headers:',
{
'authorization': `Bearer ${access_token}`,
'accept': 'application/json',
'content-type': 'application/json'
},
"result:",
result
);
ctx.body = result.data;
return ctx.body;
}
}
module.exports = ProxyController;