Facebook
From Chunky Agouti, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 226
  1. Otworzyłem terminal w katalogu take-a-rest i uzyłem komendy npm install. Powstał nowy plik
  2. package-lock.json
  3.  
  4.  
  5. Etap 1:
  6. Użyłem komendy ​ npm run 01_HttpServer by uruchomić serwer
  7. W drugim terminalu połączyłem się za pomocą http (bez s) z localhostem 3000
  8. Kod aplikacji odpowiedzialny za komunikaty:By dodać informację o czasie do odpowiedzi, zmodyfikowałem kod:
  9. Dla localhost:3000/hello:
  10. //response.send("<p>Anonymous message: Oh, Hi Mark!</p>");
  11. response.send(`<p>Anonymous message: Oh, Hi Mark! The datetime is:
  12. ${Date.now()}</p>`);
  13.  
  14.  
  15. Efekt:
  16. Dla strony głównej:response.send(`<h1>HTTP Server</h1><p>Go to /hello subpage! The datetime is:
  17. ${Date.now()}</p>`);
  18. //response.send("<h1>HTTP Server</h1><p>Go to /hello subpage!</p>");
  19.  
  20. Efekt:
  21. Dodałem obsługę zapytania GET dla /time:
  22. app.get("/time", function(request, response) {
  23. printReqSummary(request);
  24. response.send(`<p>The datetime is: ${Date.now()}</p>`);
  25. });
  26.  
  27. Wynik:
  28. Zamknąłem serwer 01_HttpServer i uruchomiłem serwer 02_UrlParameters
  29. Sprawdziłem działanie:Zwracanie losowego argumentu:
  30.  
  31. Do pliku app.js dodałem poniższy kod:
  32. function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;
  33. }
  34. // GET /X/Y/Z - return 1 of parameters
  35. app.get("/:x/:y/:z", function(request, response) {
  36. printReqSummary(request);
  37. const x = request.params.x;
  38. const y = request.params.y;
  39. const z = request.params.z;
  40. const rand = getRandomInt(0, 2);
  41. out = 0;
  42. if( rand == 0 )
  43. out = x
  44. if( rand == 1 )
  45. out = y
  46. if( rand == 2 )
  47. out = z
  48. response.send(`<p>Random input value is: ${out}</p>`);
  49. });
  50. Etap 3:
  51. Zamknąłem serwer z etapu 2. i uruchomiłem serwer 03_HttpMethods
  52. Sprawdzenie działania:
  53.  
  54. Zmodyfikowałem plik app.js by dodawanie itemów było realizowane za pomocą POST a nie
  55.  
  56. PUT
  57. /* PUT /item/:name -- add (put) new item to the collection */
  58. //app.put("/item/:name", function(request, response) {
  59. app.post("/item/:name", function(request, response) {
  60. printReqSummary(request);
  61. const itemName = request.params.name;
  62. /* Is the item in collection? */
  63. if (items.includes(itemName)) {
  64. response.send(`<p>Item "${itemName}" already in collection</p>`);
  65. } else {
  66. items.push(itemName);
  67. response.send(`<p>Item "${itemName}" added successfully</p>`);
  68. }
  69. });