Categories
JavaScript Answers

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

Spread the love

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

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

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

To get path from the request with Node.js and JavaScript, we 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).pathname;
    console.log(pathname);
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("Hello World");
    response.end();
  };

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
};

exports.start = start;

to get the path name of the request URL with url.parse(request.url).pathname.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *