[英]Why specify the path in app.use?
//app.js
var app = require('express')();
app.use('/test', require('./test'));
//test/index.js
var router = require('express').Router();
router.get('/test', function (req, res) {
res.status(200).send("success");
});
module.exports = routes;
Why does the path need to be specified in app.use and router.get? 为什么需要在app.use和router.get中指定路径? If I simply put
app.use('/', require('./test'));
如果我只是把
app.use('/', require('./test'));
instead, it seems to work just fine still. 相反,它似乎仍然可以正常工作。
With specifying router.get('/test', function (req, res)
your handler method will handle any request thats ends in /test. Depends on where the router is use()
. 通过指定
router.get('/test', function (req, res)
您的处理程序方法将处理以/ test结尾的任何请求,具体取决于路由器的use()
。
app.use(withPath, [callback...]
app.use(withPath,[callback ...]
That mount your middleware functions tests
at the speficied path /test
So your middlewares test
will be execute when the base request url path match. 将您的中间件功能
tests
安装在指定的路径/test
这样,当基本请求url路径匹配时,将执行中间件test
。
If you change this: 如果您更改此设置:
app.use('/test', require('./test'));
to this: 对此:
app.use('/', require('./test'));
then you will have the same functionality as before of using the middleware exported by the ./test
module on the routes that start with /test
so you will experience that everything will work the same, but that middleware will also handle every other route not necessarily starting with /test
which, depending on what it does and how it works, may or may not be what you want. 那么您将具有与之前在
/test
开头的路由上使用./test
模块导出的中间件相同的功能,因此您将体验到所有功能都可以正常工作,但是该中间件也可以处理其他所有路由以/test
开头,取决于您的功能和工作方式,它可能是您想要的,也可能不是。
By using some path in the app.use()
call you restrict the middleware that you're loading to that path only. 通过在
app.use()
调用中使用某些路径,可以将要加载的中间件仅限制为该路径。 When you use /
then it's like saying "every path" because every path starts with the slash - even paths that are requested for URLs that doesn't include the slash are still requested with slash, using eg with HTTP/1.1 something like: 当您使用
/
这就像说“每个路径”,因为每个路径都以斜杠开头-甚至对于不包含斜杠的URL所请求的路径仍以斜杠请求,例如使用HTTP / 1.1之类的东西:
GET / HTTP/1.1
Host: localhost
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.