· 6 years ago · Nov 08, 2019, 03:28 AM
1const http = require('http');
2function saveUserLocationToSession(request, response) {
3 let ip = request.connection.remoteAddress;//This is the IP Address
4
5 // This line changes the ip if the request had forwarded on by a 3rd party.
6 if (request.headers['x-forwarded-for']) {
7 ip = request.headers['x-forwarded-for'];
8 }
9
10 // Without this line, external api will not work with localhost
11 if (ip === '::1' || ip === '127.0.0.1') {
12 ip = '118.93.226.159';//My default wellington ip address if using localhost. (CHANGE ME)
13 }
14
15
16 const apiKey = '3dfc31fbbccdcbadc014c88afb1913d5';//Your API Key, (CHANGE ME sign up to ipstack and they give you one)
17
18 // Get the users location. (async call)
19 http.get(`http://api.ipstack.com/${ip}?access_key=${apiKey}`, (res) => {
20 res.setEncoding('utf8');
21 res.on('data', (body) => {
22 const json = JSON.parse(body);
23 //do stuff with the location
24 //console.log(JSON.stringify(json));
25 //json.region_name;
26 //json.country_name;
27 });
28 });
29}