welcome.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var express = require('express');
  2. var request = require('superagent');
  3. var config = require('../configs/config').site;
  4. var cookie = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' };
  5. var router = express.Router();
  6. /* GET home page. */
  7. router.get('/', function(req, res, next) {
  8. //var ip = req.ip;
  9. var ip = req.headers['x-real-ip'];
  10. ip2addr(ip, function(data) {
  11. var params = {
  12. head: config.title,
  13. title: 'Welcome | ' + config.title + ' - ' + config.description,
  14. description: config.description
  15. };
  16. if (data) {
  17. params['address'] = '欢迎来自' + data.area + data.location + '的朋友';
  18. }
  19. res.render('welcome', params);
  20. });
  21. });
  22. function ip2addr(ip, callback) {
  23. request
  24. .get('http://apis.juhe.cn/ip/ip2addr')
  25. .query({ ip: ip, key: '28c0a6a5eb9cca3f38bc5877a83c9868' })
  26. .set(cookie)
  27. .end(function(err, res) {
  28. var body = {};
  29. if (res && res.text) {
  30. body = res.text;
  31. } else if (res && res.body) {
  32. body = res.body;
  33. }
  34. if (!err && res.statusCode == 200) {
  35. if (typeof body === 'string') {
  36. try {
  37. body = JSON.parse(body);
  38. } catch (e) {}
  39. }
  40. callback && callback(body.result);
  41. } else {
  42. console.log(' / request info:' + err);
  43. callback && callback();
  44. }
  45. });
  46. }
  47. module.exports = router;