routing

One of the first things you need to know about a new framework is routing. Routing refers to how an application’s endpoints (URIs) respond to client requests. In simple terms, routing is defined as the path through which individual services are accessed. Before writing the route to use, analyze the entry file of the project

Analyze the entry file app.js

The app.js file is equivalent to the entry file for project startup, and there will be some common project methods and server configurations in it, which are analyzed as follows

var createError = require('http-errors'); Var express = require('express'); // Express var path = require('path'); Var cookieParser = require(' cookieParser '); Var logger = require(' Morgan '); Var indexRouter = require('./routes/index'); // import route directory rotes index var usersRouter = require('./routes/users'); // Import route directory rotes users var app = express(); Set ('views', path.join(__dirname, 'views')); // Define the page directory app.set(' View engine', 'jade'); App.use (logger('dev')); App.use (express.json()); // This is express's built-in middleware based on body-Parser // This option allows you to use the QueryString library (when false) Or the QS library (when true) to parse the URL-encoded data. // The "extension" syntax allows you to encode rich objects and arrays into A URL encoding format to achieve a JSON-like URL encoding experience //. For more information, please refer to the (qs) (https://www.npmjs.org/package/qs#readme). app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); App.use (express.static(path.join(__dirName, 'public'))); // Static resource directory app.use('/', indexRouter); App. use('/users', usersRouter); App.use (function(req, res, next) {next(createError(404)); }); App.use (function(err, req, res, Next) {// set locals to work only in the development environment res.locals. Message = err. Message; res.locals.error = req.app.get('env') === 'development' ? err : {}; / / return error HTTP status, please res. Status (err) status | | 500); Res.render ('error'); }); module.exports = app;Copy the code

Request way

Get Request routing

The get request is the easiest. Take a look at the index.js file in the routers directory and see if you can find them. Change the value of title and run NPM run start again. Open http://localhost:3000 in your browser to view the project. You can see that the previous Express has been replaced with Hello Word!

var express = require('express'); var router = express.Router(); */ router. Get ('/', function(req, res, Next) {// render('index', {title:}) {// render('index', {title:}) {// render('index', {title:}) {// render('index', {title:}); 'Hello Word! '}); }); module.exports = router;Copy the code

Route in other request modes

The other request methods are POST, PUT and DELETE

POST Request Mode

Router. post('/iwhao', function(req, res, next) {res.render('index', {title: 'Hello Word! '}); });Copy the code

PUT Request Mode

Router.put ('/iwhao', function(req, res, next) {res.render('index', {title: 'Hello Word! '}); });Copy the code

DELETE Request Mode

Router.delete ('/iwhao', function(req, res, next) {res.render('index', {title: 'Hello Word! '}); });Copy the code

Custom Route

After analyzing the routes on the home page, you can customize a new route for example

Router. get('/wh', function(req, res, next) {// render the first argument to the index. Res.render ('index', {title: 'Hello Word! '}); });Copy the code

After re-running NPM run start, visit http://localhost:3000/wh and the effect is the same as above, the description should take effect, but every time after modification, need to run the command is not feeling very inconvenient, development efficiency is also very low, the following describes a tool nodememon

nodememon

The installation

npm install nodemon
Copy the code

After the installation, change the scripts in the package.json file in the project root directory to the following code

"scripts": {
    "start": "nodemeon ./bin/www"
}
Copy the code

Then run the NPM start command to start the project. In this way, after the routing file is modified, the project is automatically restarted and the browser is refreshed to update directly

Route matching rules

/wh browser input/WH to match. In addition to full match, fuzzy match // can match/iWHAOtop, / iWHATop

router.get('/iwhao? top', function(req, res, next) { res.render('index', { title: 'Hello Word' }); });Copy the code

Matches/iWHaooTop, / iWHaoooooTop

router.get('/iwhao+top', function(req, res, next) {
  res.render('index', { title: 'Hello Word' });
});
Copy the code

Matches/iWHAOTop, /itop

router.get('/i(whao)? top', function(req, res, next) { res.render('index', { title: 'Hello Word' }); });Copy the code

Can match/iWHAOtop, /iwhao.top, /iwhao-top

router.get('/iwhao*top', function(req, res, next) {
  res.render('index', { title: 'Hello Word' });
});
Copy the code

Regular expressions are also supported

/iwhaotop, /iwhao.top, /iwhao-top router.get(/iwhao/, function(req, res,)); next) { res.render('index', { title: 'Hello Word' }); });Copy the code

The middleware

In real projects, public methods are sometimes required to intercept requests, such as some authentication before accessing more private information such as user information

If there are only one or two interfaces that need to be validated, they should be processed separately in the interfaces they need. However, if there are many interfaces that need to be validated, it is not possible to process each interface separately, so the common processing code should be made public.

Express provides a very good tool, called middleware, simply speaking middleware is a collection of some processing methods, it is very easy to use, a key point is the next in the routing method above, the following is a simple simulation example

router.get('/zjj/:status', function(req, res, next) { console.log(req.params.status); Start console.log(' I am middleware ') if(req.params && req.params.status === 'yes') {res.send(' through '); },function(req, res, next){res.send(' reject '); });Copy the code

And then the browser accesses

Printing is through http://localhost:3000/zjj/yes pages

http://localhost:3000/zjj/no pages to print is a refusal

The second parameter of router.get in the above code is a method, and the route handling method is the middleware in Express


Parameter Description

parameter describe
req Request data object Request
res Return the data object Response
next Execute the next function

The processing between start and end is just a simple simulation here, in a real project, you would definitely pull out the module separately and introduce it to identify specific permissions


Above is all the content of the first knowledge, thank you very much for seeing here, if this article is good or a little help to you, ask for like, attention, share, of course, any questions can be discussed in the comments, I will actively answer, thanks again 😁