Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. var express = require('express');
  2. var app = express();
  3. //Middleware for parsing form
  4. app.use(express.bodyParser());
  5. var quotes = [
  6. { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
  7. { author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
  8. { author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
  9. { author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
  10. ];
  11. //Simple Route
  12. app.get('/test', function(req, res) {
  13. res.type('text/plain');
  14. res.send('i am a beautiful butterfly');
  15. });
  16. //Get All quotes
  17. app.get('/', function(req, res) {
  18. res.json(quotes);
  19. });
  20. //Get Random quotes
  21. app.get('/quote/random', function(req, res) {
  22. var id = Math.floor(Math.random() * quotes.length);
  23. var q = quotes[id];
  24. res.json(q);
  25. });
  26. //Get quote by id
  27. app.get('/quote/:id', function(req, res) {
  28. if(quotes.length <= req.params.id || req.params.id < 0) {
  29. res.statusCode = 404;
  30. return res.send('Error 404: No quote found');
  31. }
  32. var q = quotes[req.params.id];
  33. res.json(q);
  34. });
  35. app.post('/quote', function(req, res) {
  36. if(!req.body.hasOwnProperty('author') ||
  37. !req.body.hasOwnProperty('text')) {
  38. res.statusCode = 400;
  39. return res.send('Error 400: Post syntax incorrect.');
  40. }
  41.  
  42. var newQuote = {
  43. author : req.body.author,
  44. text : req.body.text
  45. };
  46.  
  47. quotes.push(newQuote);
  48. res.json(true);
  49. });
  50. app.delete('/quote/:id', function(req, res) {
  51. if(quotes.length <= req.params.id) {
  52. res.statusCode = 404;
  53. return res.send('Error 404: No quote found');
  54. }
  55.  
  56. quotes.splice(req.params.id, 1);
  57. res.json(true);
  58. });
  59. console.log("Server is running at 4500");
  60. app.listen(4500);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement