weather.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var express = require('express');
  2. var request = require('superagent');
  3. var router = express.Router();
  4. var base = 'http://op.juhe.cn/onebox/weather/query?key=e0540a109f5a73e9df2981cdeb9d106f';
  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 city = req.query.city || req.body.city;
  14. city = !!city ? encodeURIComponent(city) : '';
  15. var type = (req.query.type || req.body.type) === 'xml' ? 'xml' : '';
  16. var callback = req.query.callback || req.body.callback;
  17. var url = base + '&cityname=' + city + '&dtype=' + type;
  18. var output = {
  19. data: {},
  20. status: {
  21. code: 200,
  22. message: ''
  23. }
  24. };
  25. request.get(url).set(cookie).end(function(err, response) {
  26. var body = {};
  27. if (response && response.text) {
  28. body = response.text;
  29. } else if (response && response.body) {
  30. body = response.body;
  31. }
  32. if (type !== 'xml') {
  33. if (typeof body === 'string') {
  34. try {
  35. body = JSON.parse(body);
  36. } catch (e) {
  37. output.status = {
  38. code: -1
  39. };
  40. }
  41. }
  42. output.data = (body.result && body.result.data ? body.result.data : body.result) || {};
  43. if (!err && response.statusCode === 200 && body.error_code === 0) {
  44. //
  45. } else {
  46. output.status = {
  47. code: -1,
  48. message: err || body.reason || 'Something bad happend.'
  49. };
  50. }
  51. if (callback) {
  52. return res.jsonp(output);
  53. } else {
  54. return res.json(output);
  55. }
  56. } else {
  57. res.header('content-type', 'text/xml; charset=utf-8');
  58. return res.send(body);
  59. }
  60. });
  61. }
  62. module.exports = router;