答案 0 :(得分:2)
您可以从请求标头中获取大量信息。用户所在国家将更加困难,您可能需要从请求的IP地址查找。注意:这不是完全可靠的,当然取决于获取原始请求,而不是任何代理服务器地址。您可以使用像geoip-lite这样的库(https://www.npmjs.com/package/geoip-lite)。
我会做类似的事情:
var app = express();
app.set('trust proxy', true);
var geoip = require('geoip-lite');
app.get('/test', function(req, res){
console.log('Headers: ' + JSON.stringify(req.headers));
console.log('IP: ' + JSON.stringify(req.ip));
var geo = geoip.lookup(req.ip);
console.log("Browser: " + req.headers["user-agent"]);
console.log("Language: " + req.headers["accept-language"]);
console.log("Country: " + (geo ? geo.country: "Unknown"));
console.log("Region: " + (geo ? geo.region: "Unknown"));
console.log(geo);
res.status(200);
res.header("Content-Type",'application/json');
res.end(JSON.stringify({status: "OK"}));
});
请求标头将包含许多有用的东西,例如:
Headers:
{
"host": "testhost:3001",
"user-agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-language": "en-US,en;q=0.5",
"accept-encoding": "gzip, deflate",
"connection": "keep-alive",
"upgrade-insecure-requests": "1"
}
地理对象的一个例子是:
{
country: 'US',
region: 'FL',
city: 'Tallahassee',
ll: [ 30.5252, -84.3321 ],
metro: 530,
zip: 32303
}
答案 1 :(得分:1)
您可以使用req.headers['accept-language']
作为语言,但对于您必须引用用户IP的国家/地区,它不是您可以从useragent或标题中获取的数据。