【发布时间】:2023-01-30 16:31:52
【问题描述】:
我曾尝试使用以下方法,但在托管应用程序时。我正在获取我们托管的应用程序的 IP 地址。 我也用过请求.ip和req.socket.remoteAddress但它正在返回本地主机 ip I.e ,::1
here is what I tried.
var express = require('express');
var request = require('request');
var app = express();
const IPData = require("ipdata").default;
require('dotenv').config();
const apiKey = process.env.API_KEY;
const ipdata = new IPData(apiKey);
app.get('/location', async (req, res) => {
try{
request.get('http://ipinfo.io/ip', (error, response, body) => {
if (!error && response.statusCode == 200) {
let clientIp = req.headers["x-forward-ip"] || body
console.log(body);
ipdata.lookup(clientIp)
.then((data) => {
console.log(data);
return res.json({
city: data.city,
region: data.region,
country: data.country_name,
postal: data.postal
});
})
.catch((error) => {
console.log(error);
res.status(500).send('Error looking up location');
});
}
});
}catch(error) {
console.log(error);
res.status(500).send('Error looking up location');
}
});
app.listen(8000, () => {
console.log('Server started on port 8000');
});
【问题讨论】:
-
这回答了你的问题了吗? How to determine a user's IP address in node
标签: node.js express ip ip-address