forked from jason5ng32/MyIP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipchecking.js
More file actions
50 lines (40 loc) · 1.46 KB
/
ipchecking.js
File metadata and controls
50 lines (40 loc) · 1.46 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
import { get } from 'https';
import { isValidIP } from '../common/valid-ip.js';
import { refererCheck } from '../common/referer-check.js';
export default (req, res) => {
// 限制只能从指定域名访问
const referer = req.headers.referer;
if (!refererCheck(referer)) {
return res.status(403).json({ error: referer ? 'Access denied' : 'What are you doing?' });
}
// 从请求中获取 IP 地址
const ipAddress = req.query.ip;
if (!ipAddress) {
return res.status(400).json({ error: 'No IP address provided' });
}
// 检查 IP 地址是否合法
if (!isValidIP(ipAddress)) {
return res.status(400).json({ error: 'Invalid IP address' });
}
const key = process.env.IPCHECKING_API_KEY;
if (!key) {
return res.status(500).json({ error: 'API key is missing' });
}
const lang = req.query.lang || 'en';
// 构建请求 IPCheck.ing 的 URL
const url = new URL(`https://api.ipcheck.ing/ipinfo?key=${key}&ip=${ipAddress}&lang=${lang}`);
get(url, apiRes => {
let data = '';
apiRes.on('data', chunk => data += chunk);
apiRes.on('end', () => {
try {
const originalJson = JSON.parse(data);
res.json(originalJson);
} catch (e) {
res.status(500).json({ error: 'Error parsing JSON' });
}
});
}).on('error', (e) => {
res.status(500).json({ error: e.message });
});
}