TypeError:Router.use()需要一个中间件函数,但在Function.use中得到了一个未定义的函数

时间:2018-01-24 14:19:06

标签: javascript node.js mongodb express

我是nodeJS的新手,我正在学习如何创建一个连接到mongoDB的简单api应用程序。

我阅读了一些博客并研究了一些简单的项目,我开始自己制作,但有一个小问题。我遵循了所有步骤,甚至自己检查了解决问题。

虽然,我没有成功,当我将它与api.js链接并且抛出以下错误时,问题出现在server.js中

D:\Node Js\nodeJs\userStory\node_modules\express\lib\router\index.js:458
      throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
      ^

TypeError: Router.use() requires a middleware function but got a undefined
    at Function.use (D:\Node Js\nodeJs\userStory\node_modules\express\lib\router\index.js:458:13)
    at Function.<anonymous> (D:\Node Js\nodeJs\userStory\node_modules\express\lib\application.js:220:21)
    at Array.forEach (<anonymous>)
    at Function.use (D:\Node Js\nodeJs\userStory\node_modules\express\lib\application.js:217:7)
    at Object.<anonymous> (D:\Node Js\nodeJs\userStory\server.js:26:5)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

如果有人可以查看它并指导我出错的地方会有所帮助。

&#13;
&#13;
//---Server.js
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');


var app = express();

mongoose.connect(config.database,function(err){
	if(err){
		console.log(err);
	}else{
		console.log("Connected to a database");
	}
});


app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(morgan('dev'));



app.use("/api",require('./app/route/api')(app,express));

app.get('*',function(req,res){
	res.sendFile(__dirname + '/public/views/index.html');
});

app.listen(config.port,function(err){
	if(err){
		console.log(err);
	}else{
		console.log("Listening on port "+config.port);
	}
});
&#13;
&#13;
&#13;

&#13;
&#13;
//api.js
var user = require('../model/user');

var config = require('../../config');

var secretKey = config.secretKey;

module.exports = function(app,express){

    var api = express.Router();
    //passing the data to the DB

    api.post('/signup',function(req,res){
        var user = new User({
            name:req.body.name,
            username:req.body.username,
            password:req.body.password
        });//body here is the body parser for reading the value from the DB

        //Now saving it on the DB

        user.save(function(err){
            if(err){
                res.send(err);
                return;
            }
            res.json({message:'User has been created'});
        });
    });

};
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您应该导出路由器,而不是导出功能。

var api = express.Router();
//passing the data to the DB

api.post('/signup',function(req,res){
    var user = new User({
        name:req.body.name,
        username:req.body.username,
        password:req.body.password
    });//body here is the body parser for reading the value from the DB

    //Now saving it on the DB

    user.save(function(err){
        if(err){
            res.send(err);
            return;
        }
        res.json({message:'User has been created'});
    });
});
module.exports = api;

相应地更改你的app.js

app.use("/api",require('./app/route/api'));

答案 1 :(得分:0)

在不同情况下会出现此错误。

对于我来说,当代码如下时,我会收到此错误

app.js

const { getRouter } = require('./routes/getAPIs');

...
expressServer.use("/", getRouter);

other.js

const router = expressServer.Router();
router.get("/", getData);
module.exports = router;

这里的问题是当不使用销毁方式(我们使用module.exports方法)时,使用销毁方式而不是常规方式。

解决方案是删除导入对象周围的{}。

app.js

const getRouter = require('./routes/getAPIs');

...
expressServer.use("/", getRouter);