'The "url" argument must be of type string. Received an instance of IncomingMessage in NodeJs

I am new to NodeJs, I Create custom server setup but when I Run the server setup It throw an error of this type

PS E:\MyNodeProjedt\myDream> node Server.js
node:internal/validators:120
    throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received an instance of IncomingMessage
    at new NodeError (node:internal/errors:371:5)
    at validateString (node:internal/validators:120:11)
    at Url.parse (node:url:169:3)
    at Object.urlParse [as parse] (node:url:156:13)
    at Server.<anonymous> (E:\MyNodeProjedt\myDream\Server.js:15:21)
    at Server.emit (node:events:520:28)
    at parserOnIncoming (node:_http_server:951:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17) {
  code: 'ERR_INVALID_ARG_TYPE'
}

Server.js

const http  = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');

const mimeTypes = {
    "html" : "text/html",
    "jpeg" : "text/jpeg",
    "jpg"  : "text/jpg",
    "png"  : "text/png",
    "js"  : "text/javaScript",
    "css"  : "text/css"
};
http.createServer(function(req,res){
     var  uri = url.parse(req,url).pathname;
    let fileName = path.join(process.cwd(),unescape(url));
    Console.console.log('Loading'+uri);
    let stats;
    try {
        stats = fs.lstatSync(fileName);
    } catch (error) {
        res.writeHead(404,{'Content-type':'text/plain'});
        res.write('404 Not Found\n');
        res.end();
        return;
    }
    if(stats.isFile){
        let mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
        res.writeHead(200,{'Content-type':MimeType});

        let fileStream = fs.createReadStream(fileName);
        fileStream.pipe(res);
    }else if(stats.isDirectory()){
        res.writeHead(302,{
            'location' : 'index.html'
        });
        res.end();
    }else{
        res.writeHead(500,{'Content-type':'text/plain'});
        res.write('500 Internal error\n');
        res.end();
    }
    
}).listen(3000);

This is the my custom setup of server ,but it is not working ,How to handle this type of issue I take reference from internet ,but I am not able to find my mistake how can I setup my own server setup. which is the better way to define custom server setup



Solution 1:[1]

The error is coming from this line:

var  uri = url.parse(req,url).pathname;

It needs to be:

var  uri = url.parse(req.url).pathname;

The function url.parse() expects a string (see in the error: "The "url" argument must be of type string"), but instead it's getting an object (req). Changing it to req.url gets you the url prop on the req object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allxie