代码之家  ›  专栏  ›  技术社区  ›  sk123

路由器在Express.js中返回404

  •  2
  • sk123  · 技术社区  · 6 年前

    我现在正在学习,是一个新手 Node.js REST API 目前正在接受 error 404 在postman中尝试向特定路由发送邮件以测试数据是否已成功发送到 Mongo db . 我肯定我错过了什么。我仔细检查了我所有的路线,看起来都很好。它在我发出get请求时有效,在我发出post请求时失败。

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var mongoose = require('mongoose');
    var logger = require('morgan');
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    var Developer = require('./models/developers');
    var app = express();
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(bodyParser.urlencoded({ extended: true}));
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use('/', indexRouter);
    app.use('/users', usersRouter);
    
    // Connect to DB
    mongoose.connect('mongodb://127.0.0.1:27017');
    
    // API Routes
    var router = express.Router();
    
    // Routes will be prefixed with /api
    app.use('/api', router);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;
    
    // Test Route
    router.get('/', function (req, res) {
      res.json({message: 'Welcome to my simple API!'});
    });
    
    router.route('/developers')
        .post(function (req, res) {
          var developer = new Developer(); // New instance of sa developer
          developer.firstName = req.body.firstName;
          developer.lastName = req.body.lastName;
          developer.jobTitle = req.body.jobTitle;
    
          developer.save(function (err) {
            if (err) {
              res.send(err);
            } else {
              res.json('Developer was successfully fetched');
            }
          });
        })
    
        .get(function (req, res) {
          Developer.find(function (err, developers) {
            if (err) {
              res.send(err);
            } else
              res.json(developers);
          });
        });
    
    router.route('/developer/:developer_id')
        .get(function (req, res) {
          Developer.findById(res.params.developer_id, function (err, developer) {
            if (err) {
              res.send(err);
            }
            res.json(developer);
          });
        });
    
    router.route('/developer/firstName/:firstName')
        .get(function (req, res) {
          Developer.find({firstName:res.params.firstName}, function (err, developer) {
            if (err) {
              res.send(err);
            }
            res.json(developer);
          });
        });
    

    我的模型是developer.js

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var DevelopersSchema = new Schema({
       firstName: String,
       lastName: String,
       jobTitle: String
    });
    
    module.exports = mongoose.model('Developers', DevelopersSchema);
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Shams Nahid    6 年前

    连接数据库,而不是

    mongoose.connect('mongodb://127.0.0.1:27017');
    

    使用

    mongoose.connect('mongodb://127.0.0.1:27017/yourDatabaseName');
    

    检查 doc .

    Mongoose数据库连接需要在中输入数据库名称 connect() 方法

    你的期末考试 app.js 应该是,,

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var mongoose = require('mongoose');
    var logger = require('morgan');
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    var Developer = require('./models/developers');
    var app = express();
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(bodyParser.urlencoded({ extended: true}));
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use('/', indexRouter);
    app.use('/users', usersRouter);
    
    // Connect to DB
    mongoose.connect('mongodb://127.0.0.1:27017/my_unique_data_base_name');
    
    // API Routes
    var router = express.Router();
    
    // Routes will be prefixed with /api
    app.use('/api', router);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;
    
    // Test Route
    router.get('/', function (req, res) {
      res.json({message: 'Welcome to my simple API!'});
    });
    
    router.route('/developers')
        .post(function (req, res) {
          var developer = new Developer(); // New instance of sa developer
          developer.firstName = req.body.firstName;
          developer.lastName = req.body.lastName;
          developer.jobTitle = req.body.jobTitle;
    
          developer.save(function (err) {
            if (err) {
              res.send(err);
            } else {
              res.json('Developer was successfully fetched');
            }
          });
        })
    
        .get(function (req, res) {
          Developer.find(function (err, developers) {
            if (err) {
              res.send(err);
            } else
              res.json(developers);
          });
        });
    
    router.route('/developer/:developer_id')
        .get(function (req, res) {
          Developer.findById(res.params.developer_id, function (err, developer) {
            if (err) {
              res.send(err);
            }
            res.json(developer);
          });
        });
    
    router.route('/developer/firstName/:firstName')
        .get(function (req, res) {
          Developer.find({firstName:res.params.firstName}, function (err, developer) {
            if (err) {
              res.send(err);
            }
            res.json(developer);
          });
        });
    
        2
  •  0
  •   efkan    6 年前

    如果我是对的,那么 app.use('/api', router); 什么也不做。 当有人要求 /api 端点时,应在操作结束时发送响应。代码将请求传递给 router . 路由器什么也不做。

    那么如果 createError(404) res.send() res.end() 方法 你应该把车开走 use()

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    

    因为每一次它都比其他路线先起作用。

    IMHO,使用标准的编码风格使程序流更具可读性。

    祝你好运