How to get the path from the request with Node.js?

Sometimes, we want to get the path from the request with Node.js.

In this article, we’ll look at how to get the path from the request with Node.js.

How to get the path from the request with Node.js?

To get the path from the request with Node.js, we can use the request.url property.

For instance, we write

const http = require("http");
const url = require("url");

const start = () => {
  const onRequest = (request, response) => {
    const { pathname } = url.parse(request.url);
    console.log(pathname);
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("Hello World");
    response.end();
  };
  http.createServer(onRequest).listen(8888);
};

start();

to get the request.url from the request.

Then we call url.parse to parse it to return an object with the pathname to get the request URL path.

Conclusion

To get the path from the request with Node.js, we can use the request.url property.