handlebars-ipinfo/index.ts

59 lines
1.1 KiB
TypeScript
Raw Normal View History

2017-06-02 19:00:22 +10:00
import express = require('express');
import expresshb = require('express-handlebars');
2017-06-02 20:43:16 +10:00
import http = require('http');
import https = require('https');
import promise = require('promise');
import { IPGeoJson } from './ip_geo';
2017-06-02 19:00:22 +10:00
var app = express();
2017-06-02 19:07:34 +10:00
app.engine('handlebars', expresshb({ defaultLayout: 'main' }));
2017-06-02 19:00:22 +10:00
app.set('view engine', 'handlebars');
2017-06-02 19:07:34 +10:00
2017-06-02 19:00:22 +10:00
app.get('/', function (req, res) {
2017-06-02 19:07:34 +10:00
res.render('home');
2017-06-02 20:43:16 +10:00
getIpInfo("::ffff:" + "119.17.156.106").country; //replace with req.ip
2017-06-02 19:00:22 +10:00
});
2017-06-02 20:43:16 +10:00
app.listen(3000);
function getIpInfo(ip: String): IPGeoJson {
var ipinfo: IPGeoJson = {
ip: "",
city: "",
region: "",
country: "",
loc: "",
postal: ""
};
var options = {
host: 'ipinfo.io',
port: 443,
path: '/' + ip + '/geo',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
console.log(options.path);
var callback = function (response: http.IncomingMessage) {
var str: string;
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
ipinfo = <IPGeoJson>JSON.parse(str.slice(9));
console.log(ipinfo.city);
});
}
https.get(options, callback);
return ipinfo;
}