route

以前,在app.js里可以写很多很多路由

  1. app.get('/', function(req, res) {
  2. res.render('index', { title: 'Express' });
  3. });
  4. app.get('/2', function(req, res) {
  5. res.render('index', { title: 'Express' });
  6. });
  7. app.get('/3', function(req, res) {
  8. res.render('index', { title: 'Express' });
  9. });
  10. app.get('/4', function(req, res) {
  11. res.render('index', { title: 'Express' });
  12. });
  13. app.get('/5', function(req, res) {
  14. res.render('index', { title: 'Express' });
  15. });

看着啥感觉?

路由其实就是分而治之的将具体的处理丢到单独文件中

写法

app.js

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

挂载路由

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

具体写法

  1. var express = require('express');
  2. var router = express.Router();
  3. /* GET home page. */
  4. router.get('/', function(req, res, next) {
  5. res.render('index', { title: 'Express' });
  6. });
  7. module.exports = router;
  • get
  • post
  • patch
  • delete
  • all

更多见http里的verb章节