简体   繁体   English

为什么/ users在Express和Node中路由?

[英]Why the /users route in Express and Node?

Edit: The default express app is this: 编辑:默认快递应用是这样的:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
----------------------------------------
These refer to files that look like:

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

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

module.exports = router;
------------------------------
var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

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

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

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

However, the documentation says: 但是,文档说:

// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
  res.send('Hello World');
})

// requests will never reach this route
app.get('/', function (req, res) {
  res.send('Welcome');
})

So my question, is why would a request ever make its way to the /users route when a default (ie '/' ) route has already been specified? 所以我的问题是,为什么在已经指定了默认(即'/' )路由时,请求是否会进入/users路由? Is it because routes and users are not functions? 是因为routesusers不是功能吗?

On a related note, why even specify the / if that is what is used by default each time? 在相关的说明中,为什么甚至指定/ if每次默认使用的是什么?

Lastly, the default app specifies the '/users' route: Why not just put another path in the index.js route? 最后,默认应用程序指定'/users'路由:为什么不在index.js路由中放入另一个路径? I am confused how the app can specify app.use('/users', users) and then, in the users route, specify 我很困惑应用程序如何指定app.use('/users', users) ,然后在用户路由中指定

router.get('/', function(req, res) {
  res.send('respond with a resource');
});

What does the / correspond to? /对应什么? It seemed like all requests to / would be handled by the first route (the one that use the routes default file) 似乎所有请求/将由第一个路由(使用routes默认文件的routes )处理

app.use() is middleware. app.use()是中间件。 You pass it an optional path and a function and it is the function's job to decide if it wants to pass the request on to further middleware or further routes. 您传递一个可选路径和一个函数,它是决定是否要将请求传递给更多中间件或其他路由的函数。 It does that by calling next() or if it doesn't want to pass it on, it doesn't call next() . 它通过调用next()或者如果它不想传递它来实现,它不会调用next()

So, if you have: 所以,如果你有:

app.use("/", fn);

That middleware will get called for all paths, but the code inside the function you pass it decides whether to pass the request on or not. 将为所有路径调用该中间件,但是您传递的函数内的代码决定是否传递请求。

There are two routers in the Express 4 application skeleton: routes (mounted on '/' ) and users (mounted on '/users' ). Express 4应用程序框架中有两个路由器: routes (安装在'/' )和users (安装在'/users' )。 You may use both of them or only routes or you may even add more routers. 您可以使用它们或仅使用routes或者甚至可以添加更多路由器。

app.js: app.js:

var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/users', users);  // please note the mounting point!
app.use('/', routes);

users.js users.js

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

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

module.exports = router;

Please note that router.get('/', ... ) for the users router means that the requested url is http://yourserver/users and not http://yourserver/ 请注意, users路由器的router.get('/', ... )表示请求的URL是http://yourserver/users而不是http://yourserver/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM