Node Js:Router.use()需要中间件函数但是有一个Object

时间:2016-02-22 07:46:21

标签: node.js express

我是nodejs的新手,并尝试实现路由器。我在一个单独的文件中写了路由器,比如下面显示的apiRoutes.js屁股

var express     = require('express');

// API ROUTES -------------------

// get an instance of the router for api routes
var apiRoutes = express.Router(); 
var User   = require('./app/models/user');
var jwt    = require('jsonwebtoken');


// TODO: route to authenticate a user (POST http://localhost:8080/api/authenticate)

// TODO: route middleware to verify a token

// route to show a random message (GET http://localhost:8080/api/)
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to the coolest API on earth!' });
});

// route to return all users (GET http://localhost:8080/api/users)
apiRoutes.get('/users', function(req, res) {

User.find({}, function(err, users) {
res.json(users);
});
});   

// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {

  // find the user
  User.findOne({
name: req.body.name
  }, function(err, user) {

if (err) throw err;

if (!user) {
  res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {

  // check if password matches
  if (user.password != req.body.password) {
    res.json({ success: false, message: 'Authentication failed. Wrong password.' });
  } else {

    // if user is found and password is right
    // create a token
    var token = jwt.sign(user, app.get('superSecret'), {
      expiresInMinutes: 1440 // expires in 24 hours
    });

    // return the information including token as JSON
    res.json({
      success: true,
      message: 'Enjoy your token!',
      token: token
    });
  }   
}
  });
});

module.export = apiRoutes;

在另一个文件中,比如说server.js

// =======================
// get the packages we need ============ 
// =======================
var express     = require('express');
var app         = express();
var bodyParser  = require('body-parser');
var morgan      = require('morgan');
var mongoose    = require('mongoose');

var jwt    = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User   = require('./app/models/user'); // get our mongoose model
var apiRoutes = require('./apiRoutes');


// =======================
// configuration =========
// =======================
var port = process.env.PORT || 8080; // used to create, sign, and verify tokens
mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret); // secret variable

// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// use morgan to log requests to the console
app.use(morgan('dev'));

// =======================
// routes ================
// =======================
// basic route
app.get('/', function(req, res) {
res.send('Hello! The API is at http://localhost:' + port + '/api');
});

// API ROUTES -------------------
    // we'll get to these in a second

// =======================
// start the server ======
// =======================
  app.listen(port);
console.log('Magic happens at http://localhost:' + port);

app.get('/setup', function(req, res) {

  // create a sample user
  var nick = new User({ 
  name: 'Nick Cerminara', 
  password: 'password',
  admin: true 
  });

  // save the sample user
  nick.save(function(err) {
  if (err) throw err;

console.log('User saved successfully');
res.json({ success: true });
  });
 });




// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);

app.get('/setup', function(req, res) {

  // create a sample user
  var nick = new User({ 
name: 'Nick Cerminara', 
password: 'password',
admin: true 
  });

  // save the sample user
  nick.save(function(err) {
if (err) throw err;

console.log('User saved successfully');
res.json({ success: true });
  });
});

我得到一个错误:

TypeError: Router.use() requires middleware function but got a Object
at Function.use (/home/user/jsApp/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/home/user/jsApp/node_modules/express/lib/application.js:219:21)
at Array.forEach (native)
at EventEmitter.use (/home/user/jsApp/node_modules/express/lib/application.js:216:7)
at Object.<anonymous> (/home/rawdata/jsApp/server.js:69:5)
at Module._compile (module.js:399:26)
at Object.Module._extensions..js (module.js:406:10)
at Module.load (module.js:345:32)
at Function.Module._load (module.js:302:12)
at Function.Module.runMain (module.js:431:10)
at startup (node.js:141:18)
at node.js:977:3

我想添加

module.export = apiRoutes;    
apiRoutes.js中的

将解决这个问题。但事实并非如此。那我该怎么做呢?

0 个答案:

没有答案