Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // File 02_UrlParameters/app.js
  2. const express = require("express");
  3. const app = express();
  4.  
  5. function printReqSummary(request) {
  6.   console.log(`Handling ${request.method} ${request.originalUrl}`);
  7. }
  8.  
  9. // GET / -- Show main page
  10. app.get("/", function(request, response) {
  11.   printReqSummary(request);
  12.   response.send(
  13.     `<h1>URL Parameters (and Queries)</h1><ul>
  14.       <li>Show normal message (GET /hello/segment1)</li>
  15.       <li>Show special message (GET /hello/segment1/segment2?age=NUMBER&height=NUMBER)</li>
  16.       <li>  where segment1, segment2 - any valid URL part</li>
  17.       </ul>`
  18.   );
  19. });
  20.  
  21. // GET /hello/:name -- Show normal message for a named person
  22. app.get("/hello/:name", function(request, response) {
  23.   printReqSummary(request);
  24.   // Grab URL parameters from `request.params` object
  25.   response.send(`<p>Normal message for: ${request.params.name}</p>`);
  26. });
  27.  
  28. // GET /hello/:name/:surname -- Show special message with plenty of parameters
  29. app.get("/hello/:name/:surname", function(request, response) {
  30.   printReqSummary(request);
  31.   // Grab (optional) URL queries from `request.query` object
  32.   const age = request.query.age !== undefined ? request.query.age : "unknown";
  33.   const height =
  34.     request.query.height !== undefined ? request.query.height : "unknown";
  35.   response.send(
  36.     `<p>Special message for: ${request.params.name} ${request.params.surname}
  37.       (age: ${age} years, height: ${height} cm)</p>`
  38.   );
  39. });
  40.  
  41. const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  42.  
  43. app.get("/rand/:name/:surname/", (request, response) => {
  44.   printReqSummary(request);
  45.  
  46.   const params = [];
  47.   params[0] = [request.query.age !== undefined ? request.query.age : "unknown", "age"];
  48.   params[1] = [request.query.height !== undefined ? request.query.height : "unknown", "height"];
  49.   params[2] = [request.query.weight !== undefined ? request.query.weight : "unknown", "weight"];
  50.  
  51.   const rand = getRandomInt(0, 2);
  52.   response.send(`<p>Rand parameter: ${params[rand][1]}=${params[rand][0]}</p>`);
  53. });
  54.  
  55. app.listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement