index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var http = require('http');
  2. var url = require('url');
  3. var util = require('util');
  4. var querystring = require('querystring');
  5. var mongoose = require('mongoose');
  6. var mongodbUrl = 'mongodb://' + process.env.MONGODB_USERNAME + ':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_PORT_27017_TCP_ADDR + ':' + process.env.MONGODB_PORT_27017_TCP_PORT + '/' + process.env.MONGODB_INSTANCE_NAME;
  7. var express = require('express');
  8. var app = express();
  9. var danmakuSchema = new mongoose.Schema({
  10. player: String,
  11. author: String,
  12. time: Number,
  13. text: String,
  14. color: String,
  15. type: String
  16. });
  17. var danmaku = mongoose.model('dan', danmakuSchema);
  18. app.all('*', function(req, res, next) {
  19. res.header('Access-Control-Allow-Origin', '*');
  20. res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  21. res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  22. if (req.method == 'OPTIONS') {
  23. res.send(200);
  24. }
  25. else {
  26. next();
  27. }
  28. });
  29. app.get('/', function(req, res) {
  30. mongoose.connect(mongodbUrl);
  31. var db = mongoose.connection;
  32. db.on('error',console.error);
  33. var id = url.parse(req.url,true).query.id;
  34. db.once('open', function() {
  35. danmaku.find({player: id}, function (err, data) {
  36. if (err) {
  37. console.error(err);
  38. }
  39. var json = `{"code": 1,"danmaku":[`;
  40. for (var i = 0; i < data.length; i++) {
  41. json += JSON.stringify(data[i]);
  42. if (i !== data.length - 1) {
  43. json += `,`;
  44. }
  45. }
  46. json += `]}`;
  47. res.write(json);
  48. res.end();
  49. db.close();
  50. })
  51. });
  52. });
  53. app.post('/', function (req, res) {
  54. var body = '', jsonStr;
  55. req.on('data', function (chunk) {
  56. body += chunk;
  57. });
  58. req.on('end', function () {
  59. try {
  60. jsonStr = JSON.parse(body);
  61. } catch (err) {
  62. jsonStr = null;
  63. }
  64. // jsonStr ? res.send({"status":"success", "name": jsonStr.test}) : res.send({"status":"error"});
  65. var dan = new danmaku({player: jsonStr.player, author: jsonStr.author, time: jsonStr.time, text: jsonStr.text, color: jsonStr.color, type: jsonStr.type});
  66. dan.save(function (err, d) {
  67. if (err){
  68. console.error(err);
  69. }
  70. });
  71. });
  72. });
  73. app.listen(1207);