NodeJS和ExpressJS Router.use()错误

时间:2016-04-02 19:51:04

标签: javascript node.js

我收到此错误:

TypeError: Router.use() requires middleware function but got a Object at Function. (C:/Users/peter/Desktop/mean/express-server/node_modules/express/lib/router/index.js:458:13)

我在帖子中测试了我的Api,我收到了这个错误。

当我在app.js中使用app.use('/ api',api)时,我得到了它;

app.js:

 var express = require('express');
 var path = require('path');
 var favicon = require('serve-favicon');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 var bodyParser = require('body-parser');
 var session = require("express-session");



var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/jokesApi');

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');





app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


  app.use(session({secret:'secret_3162735',saveUninitialized:true,     resave: true}));



 // The error comes from here 
 app.use('/api',api);

 app.use(function (req, res, next) {
 var session = req.session;
 var input = req.body;

 if(session.userName){
return next();
}else if(input.userName){
session.userName = input.userName;
return res.redirect('/');
}else{
req.url='/login';
return next();
 }

});

app.use('/', routes);
 app.use('/users', users);


 module.exports = app;

JokesApi.js:

 var express = require('express');
 var jokes = require('../model/jokes');
 var session = require("express-session")
 var router = express.Router();

 router.get('/joke/random',function(req,res,next){
 res.end({joke: jokes.getRandomJoke()});

 });

 router.get('/jokes',function(req,res,next){
 res.end({joke: jokes.allJokes});

 });

router.post('/joke', function(req,res){
var funJoke = req.body;
var jsonJoke = funJoke.Joke;
jokes.addJoke(jsonJoke);
res.end({funnyNewJoke: jsonJoke});
})

2 个答案:

答案 0 :(得分:2)

您未在module.exports = router; 中导出路由器。将其添加到该文件的末尾:

{{1}}

答案 1 :(得分:1)

模块jokesApi需要导出:

module.exports = router;

尝试按照此示例:http://expressjs.com/en/guide/routing.html