What is the difference between the original urlbase urlparh?

  node.js, question

clipboard.png

Url will be deleted step by step in the parsing process. For example:

// app.js
 ...
 var express = require('express');
 var users = require('users');
 var app = express();
 
 app.use('/users', users);
 
 module.exports = app;
// users.js
 var express = require('express');
 var router = express.Router();
 
 router.count = 0;
 
 //Wrong writing style
 /*
 router.get('/users/id', function(req, res, next) {
     res.send('/user/id');
 });
 */
 
 //Correct Writing
 router.get('/id', function(req, res, next) {
     res.send('/user/id');
 });
 
 module.exports = router;

With the first writing method, the browser will get 404 Not Found. The second is normal. The reason is that url will be deleted step by step in the parsing process.

Through node-inspector debugging the above example, the running values of req.url, req.originalUrl, req.baseUrl can be obtained.

// Debug Console
 > req.url
 "/id"
 > req.originalUrl
 "/user/id"
 > req.baseUrl
 "/user"

The explanation is as follows:
req.url = req.originalUrl – req.baseUrl。 It is also the matching object of the matching path passed in by router.get This also explains the results of the above example. All, post, put, and so on.

Req.originalUrl is similar to req.url The difference is that it is used to back up the original request url, so you can rewrite req.url freely to jump around without worrying about losing the original url. For example, app.use () used to mount intermediate functions rewrites req.url to compress the length of the mount point.

Req.baseUrl stores the path currently mounted by router. That is,app.use('/path', router);. At this point /path is baseUrl. Even if regular matching expressions are used when mounting, the baseUrl stores matching strings instead of regular expressions.