无法在 Node.js 上使用 URL 模块,无法调用未定义的方法“解析" [英] Can't use URL module on Node.js, cannot call method 'parse' of undefined

查看:31
本文介绍了无法在 Node.js 上使用 URL 模块,无法调用未定义的方法“解析"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 URL 获取参数,例如:

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

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

为了获取 name 参数,我看到了一些使用 url 模块的示例,如下所示:

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;

所以,首先我运行了这个命令 npm install url,依赖也依赖于 package.json 文件,但我总是得到这个错误:

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?

推荐答案

我发现了问题,我有这样的代码:

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);

并且 url 对象在 createServer 函数内部无法访问(不知道为什么),所以我只替换了这一行:

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);

这样:

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

现在工作正常.

这篇关于无法在 Node.js 上使用 URL 模块,无法调用未定义的方法“解析"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆