by Sai gowtham

How to get the full URL in Express

In this tutorial, we will learn about how to get the full url in the express route handler function.

Consider, we have the following url.

http://fun.com/users/sai

And our express route handler looks like this.

app.get('/users/sai',(req,res)=>{

})

Now, we need to get the full url inside our router handler function, instead of url path /users/sai

To do that, first we need to access the protocol, hostname, and path separately and join them all together to get the full url.

Here is an example:

app.get('/users/sai',(req,res)=>{
  const protocol = req.protocol;
  const hostname = req.host;
  const path = req.originalUrl;

  const fullURL = protocol + "://" + hostname + path;  console.log(fullURL); // http://fun.com/users/sai
})

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course