Express路由器不起作用

时间:2016-02-03 14:11:15

标签: javascript node.js express

我开始学习Node和Express,但我目前无法使用我的部分路线..这是我目前正在使用的app.js文件

编辑:这是我的更新文件,但我仍然得到了404

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

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 app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  //res.send(req.path)
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

我无法查看的路线是' / users / userlist'这是我的userlist.js路线 编辑:我已移动' / users / userlist'进入users.js路由

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');

/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
  var params = req.params[0].split("/");
  if(params.length>=2){
    var newUser = new User({username: params[0], password:params[1]});
    newUser.save(function(err, fluffy){
      if(err)
        res.send(err);
    });
  }
  res.send('Account Created!');
});


router.get('/users/userlist', function(req, res) {
    var users;
    User.find(function(err, _users){
      if(err)
        users="ERROR";
      else
        users=_users;
    });
    res.send(users);
});

module.exports = router;

当我尝试将浏览器指向http://localhost:3000/users/userlist时,我得到的是404。

1 个答案:

答案 0 :(得分:2)

在app.js中声明路由时出错,删除下面的代码。

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