This paper describes the principles express middleware to deal with the interview.
1, express installation and initialization:
npm install express-generator -g => express express-test => npm install & npm start => access can see in www.js folder bin file is port 3000, accessed through the browser localhost: 3000.
In order to facilitate development and debugging, we also need npm i nodemon cross-env --save-dev, where cross-env to set the parameters environment variables, nodemon used to monitor changes in a file, so that we do not need to modify the code when each time manually restart the service, you can avoid produce some unexpected errors. After installing two plug-ins, open package.json file, add the following code in the scripts:
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js"
{ "name": "blog-express", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www", "dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js" }, "dependencies": { "cookie-parser": "~1.4.4", "debug": "~2.6.9", "express": "~4.16.1", "http-errors": "~1.6.3", "jade": "~1.11.0", "morgan": "~1.9.1" }, "devDependencies": { "cross-env": "^6.0.3", "nodemon": "^2.0.2" } }
After the save, the command line to run npm run dev
2. Contents Introduction:
bin / www.js: Creating http service
public: static file directory, simply development interface, then this directory can be ignored.
routes: Route stored files.
views: storing html template, ignored.
3, app.js (important):
Here is the code I made some comments:
var createError the require = ( 'HTTP-errors'); // process the error information module var express = the require ( 'express'); // reference frame express var path = the require ( 'path'); // provides some gadget handle file path var cookieParser the require = ( 'Parser-Cookie'); // parse Cookie var Logger = the require ( 'Morgan'); // record access log generated log var indexRouter = the require ( './ routes / index '); // reference route var usersRouter = the require (' ./ routes / Users' ); var App = Express (); // initialize App //Engine Setup View app.set ( 'views', path.join (__ dirname, 'views')); // distal template processing, comments can not control app.set ( 'Engine View', 'Jade' ); // Register various functions app.use (Logger ( 'dev' )); app.use (express.json ()); // Data routing process directly over the post with req.body acquiring for acquiring content-type = application data / json format app.use (express.urlencoded ({Extended: to false })); // the data processing form submission over the content-type = x-www- form-urlencoded format app.use (cookieParser ()); app.use (express.static (path.join (__ dirname, 'public'))); // do not control can annotate app.use ( '/', indexRouter); //Register route '/' is spliced with the object file path routing, such as: the file path is the routing / User app.use ( '/ Users', usersRouter); // where path '/ Users' object and routing the file path splicing, such as: file path is the routing address / list was last accessed on / User / list // the catch 404 and to Forward error Handler app.use ( function (REQ, RES, Next) { // detector 404 Next (createError (404 )); }); // error Handler app.use ( function (ERR, REQ, RES, Next) { // Throws server error // SET about locals, only error in PROVIDING Development res.locals.message = err.message; // res.locals.error = req.app.get ( 'the env') === 'Development' ERR:? {}; = req.app.get res.locals.error ( 'the env') === 'dev' ERR: {};? // because the environment variable is set in package.json dev, so here was modified @ The error Page the render res.status (err.status || 500 ); res.render ( 'error' ); }); module.exports = App;
4, handling routing (important):
What route is? Make yourself Baidu!
1) get request:
New routes blog.js file folder, write code
var express = require('express'); var router = express.Router(); router.get('/list', function(req, res, next) { res.json({ errno: 0, data: [1, 2, 3] }) }); module.exports = router;
Written after writing app.js:
router.post ( '/ Login', function (REQ, res, Next) { const {username, password} = req.body // because the application express.json (), it is possible to obtain directly from req.body postdata the res .json ({ errno: 0 , Data: { username, password } }) });
Open the postman, visit HTTP: // localhost: 3000 / API / Blog / the Login , set as follows:
5, understanding of middleware (most important):
The following text is a reprint of a Gangster blog (blog address: https://blog.csdn.net/huang100qi/article/details/80220012 ):
We first analyze the input url from the browser address bar to display the process between the client data in the end what happened?
After the browser sends a request to the server, the server directly carried past data request (data information of the user input data and browser itself) by Request. Targeting properties manner. This is the middle there must be a function of these data classification done a deal has been handled well, and let the call request object used to, and this process is what we want to say the data processing function middleware. Thus, the middleware can be summarized in the following points:
1, encapsulates some processing functions of a complete event function.
2, non-built middleware need after installation, you require the file to run.
3, perhaps encapsulates some complex but it is certainly common functionality.
Light said it might not understand, look at the code you will know!
This is a validation function login:
module.exports = (req, res, next) => { if (req.session.username) { next() return } res.json({ data: '未登录' }) }
Then as a parameter in the routing function:
router.post('/new', loginCheck, (req, res, next) => { req.body.author = req.session.username const result = newBlog(req.body) return result.then(data => { res.json({ data: '登陆成功' }) }) })
这个loginCheck就是中间件。如果验证成功,就执行next(),返回“登陆成功”。这只是些简单的理解,详情请看大佬博客https://www.cnblogs.com/houfee/p/10366082.html