NodeJS路由到404而不是正确的页面

时间:2016-12-29 17:48:51

标签: node.js mongoose

我有以下代码。当我去http://localhost:4000/user时,我试图让它显示我的数据库中的用户,但我得到的只是404.我会感激一些帮助,因为我显然不理解某些东西。

app.js

    var express = require('express');
var path = require('path');
var logger = require('morgan');

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

var mongoose = require('mongoose');

var app = express();


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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/user',user);

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

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//Mongo code
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db1')
  .then(() =>  console.log('Connected to db succesfully'))
  .catch((err) => console.error(err));




module.exports = app;

app.listen(4000, function () {
  console.log('listening on port 4000!')
})

路由/ user.js的

var express = require('express');
var router = express.Router();
var userModel = require('../models/users.js');

/* GET home page. */
router.get('/user', function(req, res, next) {
  console.log("get request made");
});


router.route('/user')

  .get(function(req, res) {
        User.find(function(err, bears) {
            if (err)
                res.send(err);

            res.json(bears);
        });
    });

    .post(function(req, res) {

            var user = new User();      // create a new instance of the Bear model
            user.firstNamename = req.body.firstName;  // set the bears name (comes from the request)
        user.lastName=req.body.lastName;
        user.email=req.body.email;

            user.save(function(err) {
                if (err)
                    res.send(err);

            console.log("User created");
            });


        })

module.exports = router;

模型/ users.js

var mongoose = require('mongoose');

// Create a user schema
var userSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String,
});


module.exports = mongoose.model('User', userSchema);

1 个答案:

答案 0 :(得分:1)

这里有三个问题:

  • 首先您需要./routes/users,但路线文件为user.js,因此应该是:

    var user = require('./routes/user');
    
  • 第二,当您在应用上安装了用户中间件时,您选择将/user添加到所有用户路由(app.use('/user', user););所以当你说:

    router.route('/user').get(function ...
    

    它响应/user/user路线。所以正确的实施是:

    router.route('/').get(function ...
    

    这会回复/user

  • 第三,在删除post请求之前使用分号。

    注意 router.route('/').get(function...router.get('/', function ...完全相同。我们使用第一种模式将不同的http动词链接到一条路线。但是分号破坏了链接:

    router
      .route('/')
        .get(function ...)
        .post(function ...)
        .delete(function ...);