简体   繁体   中英

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? If I simply put 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() .

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.

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.

By using some path in the app.use() call you restrict the middleware that you're loading to that path only. 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:

GET / HTTP/1.1
Host: localhost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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