mercredi 28 juillet 2021

URL Parse NodeJS Deprecated. How to parse relative url?

I know that the same question already exists, but I don't have enough reputation to leave there a comment, so my only option is to ask again.

I am only a beginner in Node.js(bought Udemy course yesterday), so my routing is literally a bunch of if's.

Problem: url.parse is deprecated.

The problem I bumped into with answer on that question, is that to use new URL() it is important to know the exact website absolute path, which means I have to hardcode it and it is impossible to use just relative URL. (lol)?

Inside http.createServer function I have const { query, pathname } = url.parse(req.url, true);, which is supposed to give me exact path, on which I base my routing (e.g. for the website http://127.0.0.1:8000/product?id=0 I get returned query = {id: 0} and pathname = /product).

I thought to use querystring.parse, but it is also deprecated.

My code in case:

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

const server = http.createServer((req, res) => {
  const { query, pathname } = url.parse(req.url, true);
  console.log(req.url); // http://127.0.0.1:8000/product?id=0 => /product?id=0

  // Overview page
  if (pathname === "/" || pathname === "/overview") {
    res.writeHead(200, { "Content-Type": "text/html" });

    res.end('<h1>Overview page!!!</h1>');

    // Product page
  } else if (pathname === "/product") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<h1>Product page!!!</h1>');

    // Api page
  } else if (pathname === "/api") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<h1>Api page!!!</h1>');

    // Not found page
  } else {
    res.writeHead(404, { "Content-Type": "text/html" });
    res.end('<h1>Page not found!</h1>');
  }
});

server.listen(8000, "127.0.0.1", () => {
  console.log("Server started on 127.0.0.1:8000");
});



Aucun commentaire:

Enregistrer un commentaire