URL and Routing in Node

  • Post category:Node
  • Reading time:2 mins read

In this post, we will learn about the routing in Node

Routing in Node

Routing can become complicated in big applications, so in that case, we use express.js, but for now, let’s see how to do it in node.js only. We will use the built-in node module url.

URL and Routing in Node

Let’s understand this code.

Using the request.url, we will get the current URL in the browser. So, I have used some if and else if conditions based on the routing in the node application.

If pathName is ‘/’ it will respond “Home”. See the screenshot below.

node app routing

If pathName is ‘/contact’ it will respond “contact”. See the screenshot below.

node routing url

Now, let’s understand the else condition code.

So, when I type a URL which is not there in the if and else if condition then the else condition gets run and shows the page not found in <h1> tag

In this condition, I have used writeHead, which is used to send things such as statusCode (such as 400, 404, etc), ‘Content-type, or any other customized header in the response headers. When you check the API, you can see these things. See the below image.

response header in node

In this, I have sent a custom-header: ‘Abhishek’.

 

See Also:

Share this