/
index.js
47 lines (43 loc) · 1.24 KB
/
index.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
const http = require("http");
const url = require("url");
const axios = require("axios");
const port = process.env.PORT || 3000;
const APP_KEY = process.env.APP_KEY || "";
// Creating new HTTP server.
http
.createServer((req, res) => {
const { query, pathname } = url.parse(req.url, true);
const ip =
query.ip ||
(req.headers["x-forwarded-for"] || "").split(",").shift() ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
if (pathname === "/favicon.ico") {
res.writeHead(404);
res.end();
return;
}
console.log(`get location of ${ip}`);
axios
.get("http://api.map.baidu.com/location/ip", {
params: {
ak: query.ak || APP_KEY,
ip
}
})
.then(({ data }) => {
const isSuccess = data && data.status === 0;
res.writeHead(isSuccess ? 200 : 400, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(data));
})
.catch(({ response }) => {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(JSON.stringify(response.data));
});
})
.listen(port, () => {
console.log("listen on port " + port);
});