关于节点js的快速框架中的路由定义

时间:2019-05-15 11:12:45

标签: javascript node.js express

我正在我的app.js文件中设置路由。我在route / flights.js文件中通过了一条用于列出航班的路线。但是,当我在所有路由的底部定义路由时遇到的问题是我收到404错误,但是我在所有路由的顶部传递了相同的路由定义,然后它才起作用。请在下面两个文件中提供此代码,以帮助我。预先感谢。

app.js文件:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var flightRouter = require('./routes/flight');

var app = express();

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

app.use(logger('dev'));
app.use(express.json());
app.use(function(req, res, next){
  res.set('X-Powered-By', 'Flight Tracker');
  next();
});
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/flight', flightRouter);

// 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;

routes / flight.js

var express = require('express');
var router = express.Router();
var flights = require('../modules/data');
var flight = require('../modules/flight');

for (var number in flights) {
    flights[number] = flight(flights[number]);
}

router.get('/list', function (req, res, next) {
    // console.log('in list');
    res.render('flight', {
        title: 'All flights',
        flights: flights
    });
});

router.get('/:id', function (req, res, next) {
    var number = req.params.id;
    if (typeof flights[number] === 'undefined') {
        res.status(404).json({
            status: 'error'
        });
    } else {
        res.json(flights[number].getInformation());
    }
});

router.put('/:id/arrived', function (req, res, next) {
    var number = req.params.id;
    if (typeof flights[number] === 'undefined') {
        res.status(404).json({
            status: 'error'
        });
    } else {
        flights[number].triggerArrive();
        res.json({
            status: 'Done'
        });
    }
});


module.exports = router;
router.get('/list', function (req, res, next) {
    res.render('flight', {
        title: 'All flights',
        flights: flights
    });
});

上面的代码行需要在route / flight.js中其他路由的底部工作

1 个答案:

答案 0 :(得分:0)

如果您的意思是在flight.js文件中...。 这可能是因为/:id也捕获了/ list路由,因为:id没有任何约束,所以必须在/:id之前定义它: 然后,路由器将匹配/ list,如果没有匹配,它将转到/:id