mobile.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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;
  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. request.get(url).set(req.headers).end(function(err, response) {
  25. var body = {};
  26. if (response && response.text) {
  27. body = response.text;
  28. } else if (response && response.body) {
  29. body = response.body;
  30. }
  31. if (type !== 'xml') {
  32. if (typeof body === 'string') {
  33. try {
  34. body = JSON.parse(body);
  35. } catch (e) {
  36. output.status = {
  37. code: -1
  38. };
  39. }
  40. }
  41. output.data = (body.result && body.result.data ? body.result.data : body.result) || {};
  42. if (!err && response.statusCode === 200 && body.error_code === 0) {
  43. //
  44. } else {
  45. output.status = {
  46. code: -1,
  47. message: err || body.reason || 'Something bad happend.'
  48. };
  49. }
  50. if (callback) {
  51. return res.jsonp(output);
  52. } else {
  53. return res.json(output);
  54. }
  55. } else {
  56. res.header('content-type', 'text/xml; charset=utf-8');
  57. return res.send(body);
  58. }
  59. });
  60. }
  61. module.exports = router;