v1.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var express = require('express');
  2. var request = require('request');
  3. var router = express.Router();
  4. router.get('/*', function(req, res, next) {
  5. var host = req.hostname;
  6. var protocol = req.protocol;
  7. var originalUrl = req.originalUrl;
  8. var ip = req.ip.replace(/\:\:ffff\:/, '');
  9. var ip = req.ip.replace(/\:\:1/, '127.0.0.1');
  10. if (!req.query.url) {
  11. ip2address(ip, function(data) {
  12. var output = {
  13. data: {
  14. IP: ip,
  15. Info: 'Please Set URL Like This: ' + protocol + '://' + host + '/v1/?url=http[s]://YourWantProxyUrl.com'
  16. },
  17. status: {
  18. code: 200,
  19. message: ''
  20. }
  21. };
  22. if (data) {
  23. output['data']['Location'] = data.area + data.location;
  24. }
  25. return res.json(output);
  26. });
  27. } else {
  28. var url = originalUrl.split('url=')[1];
  29. url = url.indexOf('?') === -1 ? url.replace('&', '?') : url;
  30. url = /^(http|https)\:\/\//.test(url) ? url : 'http://' + url;
  31. getJSON(url, next, function(data) {
  32. var output = {
  33. data: data,
  34. status: {
  35. code: 200,
  36. message: ''
  37. }
  38. };
  39. if (req.query.callback) {
  40. return res.jsonp(output);
  41. } else {
  42. return res.json(output);
  43. }
  44. });
  45. }
  46. });
  47. router.post('/*', function(req, res, next) {
  48. res.json(req.body);
  49. });
  50. function getJSON(url, next, callback) {
  51. request(url, function(err, res, body) {
  52. body = JSON.parse(body);
  53. console.log(err);
  54. if (!err && res.statusCode == 200) {
  55. callback && callback(body);
  56. } else {
  57. var error = {
  58. data: body,
  59. status: {
  60. code: -1,
  61. message: err || body.reason || 'Something bad happened.'
  62. }
  63. };
  64. next(error);
  65. }
  66. });
  67. }
  68. module.exports = router;