Node.js Essentials: url
Table of contents
Constructing and Logging the Full URL
of an Incoming Request in Node.js
http://localhost:3000/api/v1/users?page=2
const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
console.log("Full URL: ", fullUrl);
console.log("Host: ", req.get('host'));
console.log("Original URL: ", req.originalUrl);
Explanation
req.protocol
: Returnshttp
orhttps
depending on the request protocol.req.get('host')
: Provides the host header from the request, typically including the domain and port (e.g.,localhost:3000
).req.originalUrl
: Gives you the path of the URL along with any query parameters (e.g.,/api/v1/users?page=2
).
ย