Can't use URL module on Node.js, cannot call m

2019-07-15 14:36发布

I'm trying to get parameters from a URL, for example:

http://localhost:8888/?name=test

To get name parameter I saw some samples where they use the url module like this:

var url = require('url');

var urlParts = url.parse(request.url, true);
var query = urlParts.query;

So, first I ran this command npm install url, also the dependency is on the package.json file, but I always get this error:

TypeError: Cannot call method 'parse' of undefined
at C:\Users\Administrator\git\test\app.js:28:7

Anyone has faced this problem before?

2条回答
冷血范
2楼-- · 2019-07-15 14:43

I found the problem, I had the code like this:

var http = require("http");
var url = require('url');

http.createServer(function(request, response) {
    var urlParts = url.parse(request.url, true);
    var query = urlParts.query;
}).listen(appport);

And the url object was not accessible inside the createServer function (not sure why), so I just replace this line:

var urlParts = url.parse(request.url, true);

with this:

var url_urlParts = require('url').parse(request.url, true);

and now is working fine.

查看更多
淡お忘
3楼-- · 2019-07-15 15:04

This one bit me too - my problem was that url.parse was conflicting with a local var url. I solved it like this:

import { parse as urlparse } from 'url'
var url = 'https://localhost:80'
var parsed_url = urlparse(url)

Thanks @loganfsmyth for the insight!

查看更多
登录 后发表回答