joke.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. let express = require('express');
  2. let request = require('superagent');
  3. let router = express.Router();
  4. const key = '64a40e3c55e88cc8cd66a78d030bddce';
  5. /**
  6. * Get 请求
  7. */
  8. router.get('/', function(req, res, next) {
  9. getJOKE(req, res, next);
  10. });
  11. /**
  12. * 随机获取
  13. */
  14. router.get('/rand', function(req, res, next) {
  15. getJOKE(req, res, next, 'rand');
  16. });
  17. /**
  18. * Post 请求
  19. */
  20. router.post('/', function(req, res, next) {
  21. getJOKE(req, res, next);
  22. });
  23. /**
  24. * 随机获取
  25. */
  26. router.post('/rand', function(req, res, next) {
  27. getJOKE(req, res, next, 'rand');
  28. });
  29. /**
  30. * 统一的请求
  31. */
  32. function getJOKE(req, res, next, op) {
  33. let page = req.query.page || req.body.page || 1;
  34. let pagesize = req.query.pagesize || req.body.pagesize || 1;
  35. let sort = req.query.sort || req.body.sort;
  36. let time = req.query.time || req.body.time;
  37. let type = req.query.type || req.body.type || 'pic';
  38. let callback = req.query.callback || req.body.callback;
  39. let url = '';
  40. if (!!op && op === 'rand') {
  41. if (type !== 'pic') {
  42. type = null;
  43. }
  44. url = "http://v.juhe.cn/joke/randJoke.php?key=" + key;
  45. if (!!type) {
  46. url += "&type=" + type;
  47. }
  48. } else {
  49. url = "http://japi.juhe.cn/joke/";
  50. if (!!type && type === 'text') {
  51. url += "content/text.from?key=";
  52. } else {
  53. url += "img/text.from?key=";
  54. }
  55. url += key + "&page=" + page + "&pagesize=" + pagesize;
  56. if (!!sort && !!time) {
  57. url += "&sort=" + sort + "&time=" + time;
  58. url = url.replace(/text/, 'list');
  59. }
  60. }
  61. let output = {
  62. data: {},
  63. status: {
  64. code: 200,
  65. message: ''
  66. }
  67. };
  68. request.get(url).end(function(err, response) {
  69. let body = response.text || response.body;
  70. if (typeof body === 'string') {
  71. try {
  72. body = JSON.parse(body);
  73. } catch (e) {
  74. output.status = {
  75. code: -1
  76. };
  77. }
  78. }
  79. output.data = (body.result && body.result.data ? body.result.data : body.result) || {};
  80. if (!err && response.statusCode === 200 && body.error_code === 0) {
  81. //
  82. } else {
  83. output.status = {
  84. code: -1,
  85. message: err || body.reason || 'Something bad happend.'
  86. };
  87. }
  88. if (callback) {
  89. return res.jsonp(output);
  90. } else {
  91. return res.json(output);
  92. }
  93. });
  94. }
  95. module.exports = router;