Node.JS未定义不是所需模块的功能 [英] Node.JS undefined is not a function on required module

查看:141
本文介绍了Node.JS未定义不是所需模块的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个我创建的名为user.js.该用户的代码是:

I'm trying to use a class that I created called user.js. The code for this user is:

function User(){};

User.prototype.addUser = function(){
    //Do stuff
    return 0;
};

module.exports = User;

我将其包含在我的index.js路由文件中,如下所示:

I'm including it in my index.js route file, which looks like this:

var config = require('../lib/config');
var db = require('../lib/db');
var User = require('../lib/user');
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

/* GET create user. */
router.get('/newuser', function(req, res, next) {
    *****var newuser = User.addUser();*****

    res.render('index', {   
                        user: newuser
                    });
});

module.exports = router;

但是,当我访问localhost / newuser时,我收到以下错误: TypeError:undefined不是函数。这个错误被抛出在我上面标有5个星号的行中的index.js中。

However, when I visit localhost/newuser, I get the following error: TypeError: undefined is not a function. This error is being thrown in index.js on the line I marked with 5 asterisks above.

推荐答案

您正在定义一个名为 User()并导出它。但是,当您 require('../ lib / user')时,您会得到构造函数,但是您不会使用它来构造一个新对象,所以不要实际上有一个类型为 User 的对象,你只需要构造函数,因此没有方法 addUser()构造函数。

You are defining a constructor named User() and exporting it. But, then when you require('../lib/user'), you get the constructor function, but you never construct a new object with it so you don't actually have an object of type User, you just have the constructor and thus there is no method addUser() on the constructor.

而不是这样:

var User = require('../lib/user');

您可以像这样调用构造函数:

you can call the constructor function like this:

var u = require('../lib/user');
var User = new u();

或者,如果您不需要再创建另一个,您可以一行完成所有操作: / p>

Or, if you never need to make another one, you can do it all in one line:

var User = new (require('../lib/user'))();

这篇关于Node.JS未定义不是所需模块的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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