server.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. http = require('http');
  2. var history = [];
  3. var errorMessages = {
  4. "0": "All fine",
  5. "-1": "No space left in DB",
  6. "-2": "Wrong data",
  7. "-3": "Apocalypse",
  8. "-4": "REALLY Wrong data",
  9. };
  10. var RPCFuncs = {
  11. getMessages: function(data){
  12. var messageId = +data.messageId;
  13. return history.slice(messageId);
  14. },
  15. addMessage: function(data){
  16. history.push(data);
  17. }
  18. };
  19. server = http.createServer(function(req, res){
  20. if (req.method == "POST"){
  21. var body = '';
  22. req.on('data', function (data) {
  23. body += data;
  24. });
  25. req.on('end', function () {
  26. console.log("Body: " + body);
  27. try{
  28. var data = JSON.parse(body);
  29. }
  30. catch (e){
  31. console.log("wrong JSON");
  32. var errorCode = -4;
  33. res.end(JSON.stringify({errorCode: errorCode, errorMessage: errorMessages[errorCode]}));
  34. return;
  35. }
  36. var timestamp =(new Date()).getTime();
  37. //var errorCode = 0 - Math.floor(Math.random()*4)
  38. //res.end(JSON.stringify({errorCode: errorCode, errorMessage: errorMessages[errorCode]}));
  39. if ("func" in data){
  40. if (data.func in RPCFuncs){
  41. var func = data.func;
  42. delete data.func;
  43. data.timestamp = timestamp;
  44. var result = {data: RPCFuncs[func](data), nextMessageId: history.length};
  45. console.log("answer on request:");
  46. console.log(JSON.stringify(result));
  47. res.end(JSON.stringify(result));
  48. }
  49. else {
  50. console.log("no func in functions array" + body);
  51. }
  52. }
  53. else {
  54. console.log("no func key in data:" + body);
  55. }
  56. });
  57. res.setHeader('Access-Control-Allow-Origin', '*');
  58. res.setHeader('Access-Control-Request-Method', '*');
  59. res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST');
  60. res.setHeader('Access-Control-Allow-Headers', '*');
  61. res.writeHead(200, {'Content-Type': 'text/json'});
  62. //res.end('post received');
  63. }
  64. });
  65. port = 8070;
  66. host = '164.138.30.21';
  67. server.listen(port, host);
  68. console.log("Listen...");