forked from jason5ng32/MyIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipsb.js
55 lines (48 loc) · 1.63 KB
/
ipsb.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
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?' });
}
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 url = new URL(`https://api.ip.sb/geoip/${ipAddress}`);
get(url, apiRes => {
let data = '';
apiRes.on('data', chunk => data += chunk);
apiRes.on('end', () => {
try {
const originalJson = JSON.parse(data);
const modifiedJson = modifyJsonForIPSB(originalJson);
res.json(modifiedJson);
} catch (e) {
res.status(500).json({ error: 'Error parsing JSON' });
}
});
}).on('error', (e) => {
res.status(500).json({ error: e.message });
});
};
function modifyJsonForIPSB(json) {
return {
ip: json.ip,
city: json.city,
region: json.region ? json.region : json.city,
country: json.country_code,
country_name: json.country,
country_code: json.country_code,
latitude: json.latitude,
longitude: json.longitude,
asn: "AS" + json.asn,
org: json.isp
};
}