Advertisement
Sora952

Parsing url

May 18th, 2020
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const http = require('http');
  2. const port = 8000;
  3. const url = require('url');
  4.  
  5. // const requestHandler = (request, response) => {
  6. //   console.log(request.url);
  7. //   response.end('Hello Node.js Server!');
  8. // };
  9.  
  10. // const requestHandler = (request, response) => {
  11. //   console.log(request.url);
  12. //   if (request.url === '/') {
  13. //     response.end('Hello Node.js Server!');
  14. //   } else if (request.url === '/about') {
  15. //     response.end('This demonstrates routing with Node.js.');
  16. //   } else {
  17. //     response.end('Default page (URLs other than / and /about)');
  18. //   }
  19. // };
  20.  
  21. const requestHandler = (request, response) => {
  22.   // The URL we want to parse (= analyze)
  23.   const exampleUrl = request.url;
  24.  
  25. // Check url.parse's doc for the meaning of parameters
  26.   const parsedUrl = url.parse(exampleUrl, true);
  27.  
  28. // Show the results
  29.   console.log('Parsed query string:');
  30.   console.log(parsedUrl.query); // { name: 'Jane', city: 'Boston' }
  31.  
  32.   const {name, city} = parsedUrl.query;
  33.  
  34.   if (request.url === '/') {
  35.     response.end('Hello Node.js Server!');
  36.   } else if (request.url === '/about') {
  37.     response.end('This demonstrates routing with Node.js.');
  38.   } else if ((name) && (!city)) {
  39.     response.end(`Hello ${name}, from (Please, you do enter a city)`);
  40.   } else if ((city) && (!name)) {
  41.     response.end(`Hello, (Please write your name) from ${city}.`);
  42.   } else if ((name) && (city)) {
  43.     response.end(`Hello, ${name} from ${city}.`);
  44.   } else {
  45.     response.end('Default page (URLs other than / and /about)');
  46.   }
  47.  
  48. };
  49.  
  50. const server = http.createServer(requestHandler);
  51.  
  52. server.listen(port, (err) => {
  53.   if (err) {
  54.     console.error('Something bad happened');
  55.   } else {
  56.     console.log(`server is listening on ${port}`);
  57.   }
  58. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement