mobile.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var express = require('express');
  2. var request = require('superagent');
  3. var router = express.Router();
  4. var base = 'http://apis.juhe.cn/mobile/get?key=9f719ab7014f2cbdc7b394edf70d0f76';
  5. 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' };
  6. router.get('/', function(req, res, next) {
  7. getMobile(req, res, next);
  8. });
  9. router.post('/', function(req, res, next) {
  10. getMobile(req, res, next);
  11. });
  12. function getMobile(req, res, next) {
  13. var type = req.query.type || req.body.type || 'json';
  14. var phone = req.query.phone || req.body.phone;
  15. var callback = req.query.callback || req.body.callback;
  16. var url = base + '&phone=' + phone + '&dtype=' + type;
  17. var output = {
  18. data: {},
  19. status: {
  20. code: 200,
  21. message: ''
  22. }
  23. };
  24. if(!phone){
  25. output['status']={
  26. code:-1,
  27. message:'phone number is empty.'
  28. };
  29. if (callback) {
  30. res.jsonp(output);
  31. } else {
  32. res.json(output);
  33. }
  34. return;
  35. }
  36. request.get(url).set(cookie).end(function(err, response) {
  37. var body = {};
  38. if (response && response.text) {
  39. body = response.text;
  40. } else if (response && response.body) {
  41. body = response.body;
  42. }
  43. if (type !== 'xml') {
  44. if (typeof body === 'string') {
  45. try {
  46. body = JSON.parse(body);
  47. } catch (e) {
  48. output.status = {
  49. code: -1
  50. };
  51. }
  52. }
  53. output.data = (body.result && body.result.data ? body.result.data : body.result) || {};
  54. if (!err && response.statusCode === 200 && body.error_code === 0) {
  55. //
  56. } else {
  57. output.status = {
  58. code: -1,
  59. message: err || body.reason || 'Something bad happend.'
  60. };
  61. }
  62. if (callback) {
  63. res.jsonp(output);
  64. } else {
  65. res.json(output);
  66. }
  67. } else {
  68. res.header('content-type', 'text/xml; charset=utf-8');
  69. res.send(body);
  70. }
  71. });
  72. }
  73. module.exports = router;