welcome.js 1.3 KB

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