Advertisement
Guest User

Untitled

a guest
Dec 16th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express') // Popular web framework for Node.js
  2. var bodyParser = require('body-parser') // Auto parses body of post and put requests
  3. var morgan = require('morgan') // Logs HTTP requests to the console
  4. var app = express()
  5. app.use(express.static('static'));    // makes the files in /static folder available
  6. app.use(bodyParser.urlencoded({ extended: true })) //
  7. app.use(bodyParser.json());                        // Hooking on functions that will we called for each request
  8. app.use(morgan('dev'));                            //
  9.  
  10. var data = require('./data');
  11. var port = 19201;
  12. // HTTP SERVER
  13. app.listen(port, function () {
  14.   console.log('Message app listening on port '+port+'!')
  15. });
  16.  
  17. // HOME PAGE
  18. app.get('/', function (request, response) {
  19.   response.sendFile(__dirname + '/index.html');
  20. });
  21.  
  22. // MESSAGES ENDPOINT
  23. app.post('/messages', function(request, response) {
  24.   console.log(request.body);
  25.   _username = request.body.userName;
  26.   _text = request.body.text;
  27.  
  28.   if(_username == "" || _text == "" )
  29.     {
  30.         response.sendStatus(400);
  31.     }
  32.   else
  33.   {
  34.       data.addMessage(_username, _text);
  35.       response.sendStatus(201);
  36.   }
  37.  
  38. });
  39.  
  40. app.delete('/messages/:id', function(request, response)
  41. {
  42.   var _id = request.params.id;
  43.   if(data.removeMessage(_id) == null)
  44.   {
  45.     response.sendStatus(404);
  46.   }
  47.   else
  48.   {
  49.     response.json(data.removeMessage(_id));
  50.     response.sendStatus(200);
  51.   }
  52.  
  53.  
  54.  
  55. })
  56.  
  57. app.get('/messages', function(request, response)
  58. {
  59.   response.json(data.messages);
  60. });
  61.  
  62. app.get('/messages/:id', function(request, response)
  63. {
  64.   var id = request.params.id;
  65.  
  66.   if(data.getMessageById(id)==null)
  67.   {
  68.     response.sendStatus(404);
  69.   }
  70.   else
  71.   {
  72.       response.json(data.getMessageById(id))
  73.   }
  74. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement