TypeError:require(...)不是函数

时间:2016-03-19 21:11:22

标签: javascript node.js module export typeerror

我收到以下错误:

var userModel = require("./models/user.model.js")();
                                                 ^

TypeError: require(...) is not a function
at module.exports 
at Object.<anonymous> 
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)

当我尝试require 2个文件时,使用以下代码:

module.exports = function (app) {
  "use strict";

  var userModel = require("./models/user.model.js")();
  var formModel = require("./models/form.model.js")();

  require("./services/user.service.server.js")(app, userModel);
  require("./services/form.service.server.js")(app, formModel);
  require("./services/field.service.server.js")(app, formModel);
};

我是新手,我无法理解这个问题。有人可以向我解释并帮我找到解决方案吗?

编辑:添加user.services.server.js:

module.exports = function(app, userModel) {
"use strict";

app.post('/api/assignment/user', createUser);
app.get('/api/assignment/user', findUsers);
app.get('/api/assignment/user/:id', findUserById);
app.put("/api/assignment/user/:userId", updateUserById);
app.delete("/api/assignment/user/:userId", deleteUserById);

function createUser(req, res) {
    var newUser = userModel.createUser(req.body);
    res.json(newUser);
}

function findUsers(req, res) {
    if (req.query.username) {
        if (req.query.password) {
            findUserByCredentials(req, res);
        } else {
            findUserByUsername(req, res);
        }
    } else {
        var users = userModel.findAllUsers();
        res.json(users);
    }
}

function findUserById(req, res) {
    var userId = parseInt(req.params.id);
    var user = userModel.findUserById(userId);
    res.json(user);
}

function findUserByUsername(req, res) {
    var username = req.query.username;
    var user = userModel.findUserByUsername(username);
    res.json(user);
}

function findUserByCredentials(req, res) {
    var credentials = {
        username: req.query.username,
        password: req.query.password
    };
    var user = userModel.findUserByCredentials(credentials);
    res.json(user);
}

function updateUserById(req, res) {
    var userId = parseInt(req.params.id);
    var newUser = userModel.updateUser(userId, req.body);
    res.json(newUser);
}

function deleteUserById(req, res) {
    var userId = parseInt(req.params.id);
    userModel.deleteUser(userId);
    res.send(200);
}

}();

1 个答案:

答案 0 :(得分:2)

这是因为您在()的末尾添加了require。删除它们。