TypeError("Parameter 'url' must be a string While Parsing a URL

3,970 views
Skip to first unread message

JPJen

unread,
Jan 10, 2014, 2:50:00 PM1/10/14
to nod...@googlegroups.com

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.

José F. Romaniello

unread,
Jan 10, 2014, 3:07:16 PM1/10/14
to nod...@googlegroups.com
if req is request http://github.com/mikeal/request , it doesn't have a url property. 

What are you trying to do?


2014/1/10 JPJen <caroli...@gmail.com>
--
--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to
nodejs+un...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en
 
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Steve Milburn

unread,
Jan 10, 2014, 3:13:38 PM1/10/14
to nod...@googlegroups.com
You need to parse the URL inside of your routing function, where the req variable lives.

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

And yes, you can then compare the path to a string.

JPJen

unread,
Jan 10, 2014, 5:07:31 PM1/10/14
to nod...@googlegroups.com
What I am interested in doing is to parse a URL, which is http://localhost:port_number/lens/v1/ping, that is sent from a browser.  I would like to compare the pathname of the URL with "/lens/v1/ping" (I hope that I could use == to compare).  If the comparison result is true, I am going to return Status 200 as the response to the browser window..  Somehow, I cannot write that URL parsing statement correctly.  I keep getting TypeError.




On Friday, January 10, 2014 2:50:00 PM UTC-5, JPJen wrote:

Ryan Schmidt

unread,
Jan 10, 2014, 6:22:21 PM1/10/14
to nod...@googlegroups.com

On Jan 10, 2014, at 16:07, JPJen <caroli...@gmail.com> wrote:

> What I am interested in doing is to parse a URL, which is http://localhost:port_number/lens/v1/ping, that is sent from a browser. I would like to compare the pathname of the URL with "/lens/v1/ping" (I hope that I could use == to compare). If the comparison result is true, I am going to return Status 200 as the response to the browser window.. Somehow, I cannot write that URL parsing statement correctly. I keep getting TypeError.

As José said, Mikael’s request module does not have a “url” property. Therefore it is not a string. That is why you are getting a type error.

I think you’re getting confused between Mikael’s request module:

var req = require('request');

and the req object that node gives you as reference for each request, for instance in the example shown on the nodejs homepage:

var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1’);

Other than the name “req”, these two variables have nothing in common.

JPJen

unread,
Jan 13, 2014, 10:38:16 AM1/13/14
to nod...@googlegroups.com
Thanks all for your attention.  I realize my confusion now. 

I still need help because I am new to the Node.js.

I am trying to add a new URL path to a piece of existing code (shown below).  The existing code already has server configuration code but the code looks different from the example that is showing in the Node.js home page.

The new URL path is "/lens/v1/ping" from the browser window. 

If that is the URL path received, I am supposed to send a response Status 200 back to the browser.

I am having difficulties to fit this new URL path and its associated code to the existing code (show below) and I am seeking help.  Thank you very much.

/**

* Entry point for the RESTFul Service.

*/

var express = require('express')

    var config = require('config');

var _ = require('underscore');

var bodyParser = require("vcommons").bodyParser;

// Export config, so that it can be used anywhere

module.exports.config = config;

 

var Log = require('vcommons').log;

var logger = Log.getLogger('SUBSCRIBE', config.log);

var http = require("http");

var https = require("https");

var fs = require("fs");

var cluster = require("cluster");

var numCPUs = require('os').cpus().length;

 

if (cluster.isMaster) {

    // Fork workers.

    for (var i = 0; i < numCPUs; i++) {

        cluster.fork();

    }

 

    cluster.on('online', function (worker) {

        logger.info('A worker with #' + worker.id);

    });

    cluster.on('listening', function (worker, address) {

        logger.info('A worker is now connected to ' + address.address + ':' + address.port);

    });

    cluster.on('exit', function (worker, code, signal) {

        logger.info('worker ' + worker.process.pid + ' died');

    });

} else {

    logger.info("Starting Subscription Application");

    createApp();

}

 

// Create Express App

function createApp() {

    var app = express();

 

    app.configure(function () {

        // enable web server logging; pipe those log messages through winston

        var winstonStream = {

            write : function (message, encoding) {

                logger.trace(message);

            }

        }; // Log

        app.use(bodyParser({}));

        app.use(app.router);

 

        if (config.debug) {

            app.use(express.errorHandler({

                    showStack : true,

                    dumpExceptions : true

                }));

        }

    });


    // Include Router

    var router = require('../lib/router')();


    // Subscribe to changes by certain domain for a person

    app.post('/lens/v1/:assigningAuthority/:identifier/*', router.submitRequest);

   

    // Listen

    if (!_.isUndefined(config.server) || !_.isUndefined(config.secureServer)) {

        if (!_.isUndefined(config.server)) {

            http.createServer(app).listen(config.server.port, config.server.host, function () {

                logger.info("Subscribe server listening at http://" + config.server.host + ":" + config.server.port);

            });

        }

 

        if (!_.isUndefined(config.secureServer)) {

            https.createServer(fixOptions(config.secureServer.options), app).listen(config.secureServer.port, config.secureServer.host, function () {

                logger.info("Subscribe server listening at https://" + config.secureServer.host + ":" + config.secureServer.port);

            });

        }

    } else {

        logger.error("Configuration must contain a server or secureServer.");

        process.exit();

    }

}

 

function fixOptions(configOptions) {

    var options = {};

 

    if (!_.isUndefined(configOptions.key) && _.isString(configOptions.key)) {

        options.key = fs.readFileSync(configOptions.key);

    }

 

    if (!_.isUndefined(configOptions.cert) && _.isString(configOptions.cert)) {

        options.cert = fs.readFileSync(configOptions.cert);

    }

 

    if (!_.isUndefined(configOptions.pfx) && _.isString(configOptions.pfx)) {

        options.pfx = fs.readFileSync(configOptions.pfx);

    }

 

    return options;

}

// Default exception handler

process.on('uncaughtException', function (err) {

    logger.error('Caught exception: ' + err);

    process.exit()

});

// Ctrl-C Shutdown

process.on('SIGINT', function () {

    logger.info("Shutting down from  SIGINT (Crtl-C)")

    process.exit()

})

// Default exception handler

process.on('exit', function (err) {

    logger.info('Exiting.. Error:', err);

});





On Friday, January 10, 2014 2:50:00 PM UTC-5, JPJen wrote:

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.    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'); }

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')) {
Reply all
Reply to author
Forward
0 new messages