forked from jason5ng32/MyIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.js
62 lines (47 loc) · 1.98 KB
/
map.js
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
import { get } from 'https';
// 验证请求合法性
function isValidRequest(req) {
const isLatitudeValid = /^-?\d+(\.\d+)?$/.test(req.query.latitude);
const isLongitudeValid = /^-?\d+(\.\d+)?$/.test(req.query.longitude);
const isLanguageValid = /^[a-z]{2}$/.test(req.query.language);
const isCanvasModeValid = /^(CanvasLight|RoadDark)$/.test(req.query.CanvasMode);
if (!isLatitudeValid || !isLongitudeValid || !isLanguageValid || !isCanvasModeValid) {
return false;
} else {
return true;
}
}
export default (req, res) => {
// 限制只能从指定域名访问
const allowedDomains = ['localhost', ...(process.env.ALLOWED_DOMAINS || '').split(',')];
const referer = req.headers.referer;
if (referer) {
const domain = new URL(referer).hostname;
if (!allowedDomains.includes(domain)) {
return res.status(403).json({ error: 'Access denied' });
}
} else {
return res.status(403).json({ error: 'What are you doing?' });
}
// 检查请求是否合法
if (!isValidRequest(req)) {
return res.status(400).json({ error: 'Invalid request' });
}
// 使用 req.query 获取参数
const { latitude, longitude, language, CanvasMode } = req.query;
if (!latitude || !longitude || !language) {
return res.status(400).json({ error: 'Missing latitude, longitude, or language' });
}
const mapSize = '800,640';
const pp = `${latitude},${longitude};46`;
const fmt = 'jpeg';
const dpi = 'Large';
const apiKeys = (process.env.BING_MAP_API_KEY || '').split(',');
const apiKey = apiKeys[Math.floor(Math.random() * apiKeys.length)];
const url = `https://dev.virtualearth.net/REST/v1/Imagery/Map/${CanvasMode}/${latitude},${longitude}/5?mapSize=${mapSize}&pp=${pp}&key=${apiKey}&fmt=${fmt}&dpi=${dpi}&c=${language}`;
get(url, apiRes => {
apiRes.pipe(res);
}).on('error', (e) => {
res.status(500).json({ error: e.message });
});
};