'TypeError - Parameter must be a string While Parsing a URL

I have two questions.

I have a code snippet below

var http = require('http'),      
    https = require('https'),
    crypto = require('crypto');
var S = require('string');
var url = require('url');
var req = require('request');

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

The error message points at

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

saying throw new TypeError("Parameter 'url' must be a string. not " + typeof url)

What is wrong with that statemet? Do I have to put that statement in a function? But, I do not know what function I should create for dong url parsing.

My second question refers to the code snippet below. Can I compare the path that I extract from a URL and compare it with a string using == ?

if ((S(path) == '/lens/v1/ping') || (S(path) == '/lens/v1/PING')) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('The lens route is up and running!\n');
    res.end();
} else {
    res.writeHead(404, 'Not Found');
    res.end('HTTP 1.1 404/Not Found');
}

Thank you very much in advance.



Solution 1:[1]

var req = require('request')

https://github.com/mikeal/request/blob/master/request.js

req is a function...

And yes, if you have a request object, then path would be a string and you can use == or ===.

Solution 2:[2]

If req is request module, then url does not exist in req. So you must get error.

You need to parse the URL inside of your routing function, where the req variable lives.

See below example:

Example 1:

app.get("/page", function(req, res) {
  var uri = url.parse(req.url).pathname;
}

Example 2:

http.createServer(function(req, res){
  var uri = url.parse(req.url).pathname;
}

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 farvilain
Solution 2 Ari4