NodeJS - Requesting URL Path, Method and Query from Simple Web Server

in #teammalaysia7 years ago

nodejs2.png

After we got our Simple NodeJS Web Server up and running, we can add more code to request URL path, method and query.

And the steps are 5:

  1. Add another NodeJS dependencies which is: const url = require('url');

  2. We create parsed URL object inside the http server function: let parsedUrl = url.parse(req.url,true);

  3. From the parsed URL we get the URL path: let path = parsedUrl.pathname;

  4. From the http request we get the method: let method = req.method.toLowerCase();

  5. Print the output with console.log.

Below are the full code:

//dependcies
const http = require('http');
const url = require('url');

// Create the server
let server = http.createServer( function(req,res){

    //Get URL and parse it
    let parsedUrl = url.parse(req.url,true); 

   //Get the URL path
   let path = parsedUrl.pathname;


   //Get query String as an object
   let queryStringObject = parsedUrl.query;

    //Get the HTTP method
    let method = req.method.toLowerCase();
 
    //send respond
    res.end('Hello world\n');

    // Log the request path
    console.log('Request received on path:' + path + 'with method ' + method);
    console.log('With these query String parameters: ', queryStringObject);
  });

// The server created listen to port
server.listen(3000,()=>{
    console.log('Server listening on port 3000');
});
Sort:  

WARNING - The message you received from @ekpenyong is a CONFIRMED SCAM!
DO NOT FOLLOW any instruction and DO NOT CLICK on any link in the comment!

For more information about this scam, read this post:
https://steemit.com/steemit/@arcange/phishing-site-reported-steembottracker-dot-trade

If you find my work to protect you and the community valuable, please consider to upvote this warning or to vote for my witness.