0

我是 node.js 和 express 的新手,我想知道我是否需要 app.js 中的某些内容,我是否仍然需要在 index.js 和 user.js 等独立路由文件中需要它

4

1 回答 1

1

快递项目的示例结构:

/example
    app.js
    /bin
       www
    package.json
    /node_modules
        [about 4,500 subdirectories and files]
    /public
       /images
       /javascripts
       /stylesheets
          style.css
    /routes
       index.js
       users.js
    /views
       error.pug
       index.pug
       layout.pug

/app.js:

 var createError = require('http-errors');
 var express = require('express');
 var path = require('path');
 var logger = require('morgan');

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

 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(express.static(path.join(__dirname, 'public')));

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

  // 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/index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

module.exports = router;

/routes/user.js:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
于 2018-12-09T14:37:28.760 回答