express is easy to use

Keywords: Session npm JSON Redis

Introducing express

npm install express --save 

express-generator

This is a generator to generate express, through which we can quickly build an express architecture without having to build a tedious one.

npn install express-generator -g 

Note: - g means global installation, if not global installation, it must be executed in the express-generator file directory, which is very cumbersome, but if global installation, we can execute this command in any directory.

Quickly build projects using express-generator

express myapp		//The default template engine used here is jade. If you want to use the ejs template engine, it can be npm-e myapp, where-e represents the use of the ejs template engine.
cd myapp 			//That is, enter the myapp folder
npm install			//Install dependencies in package.json

After installing the dependencies, we can see that the dependencies in package.json are as follows:

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "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"
  }
}

body-parser must be used when post ing requests; cookie-parser must be used when cookies are processed; debug module is used for debugging, similar to console.log; express ion is not to mention; jade is a template engine module, which is also very important for server-side languages. morgan is a log module, which is used to print req requests in the background, and so on. It is very similar to debug module, but debug module is used to replace console. log, while morgan is mainly used to view requests.

Start the application

set DEBUG=myapp:* & npm start		//Start the debug module and print some debug logs for us to manage the background.

npm start							//Start without debug module

Use of routes files

In fact, it is also possible not to use routes files, but in actual development, routing files are often hundreds of thousands. If all of them are placed in app.js, it is not difficult to imagine how bloated app.js will be, so we need to put different routes under different files.

For the template generated by express-generator, app.js is as follows:

var express = require('express'); 
var app = express(); 
var indexRouter = require('./routes/index'); 
var userRouter = require('./routes/users'); 
app.use('/', indexRouter); 
app.use('/users', userRouter); 
app.listen(3000);

Then go to index under routes and we can see:

var express = require('express'); 
var router = express.Router(); 
router.get('/', function(req, res) { 
	res.send('hello, express'); 
}); 
module.exports = router;

router is an example of express.Router().

The same is true for users under routes:

var express = require('express'); 
var router = express.Router(); 
router.get('/:name', function(req, res) { 
	res.send('hello, ' + req.params.name); 
}); 
module.exports = router;

So we can manage the routing very well, of course, in the actual project, we are not really as long as the two routes, as long as we ensure that a path corresponds to a routing file, so we can manage the routing very well.

The difference between app.use and app.all

When using express framework, app.use and app.all are often found in app.js. Let's look at the similarities and differences between them.

Let's start with a code example:

const express = require('express');
const app = express();

app.use('/a',function(req,res,next){
    console.log('111');
    next();
});
app.all('/a',function(req,res,next){
    console.log('222');
    res.end("completion of enforcement")
});

When we request / a routing, we output 111 and 222 in turn, and then the browser side shows that the execution is complete.

app.use

app.use is mainly used in middleware in general. use('/a') can match only with a path starting with / A. If there are paths / a/b, / a/b/c, it will be processed by this function, that is to say, 111 will be output, which is equivalent to the matching effect with itself.

The path ahead of app.use can be omitted. If omitted, it means matching all paths. Therefore, it is generally applied to middleware processing, such as GZip compression enabled on websites:

const compression = require('compression');
app.use(compression());

If we want to deal with paths that start with a string, we can write in the following way. Take session as an example:

const session = require("express-session")
app.use("/hehe",session({
    name: 'sessionID',//The key name stored in the user cookie
    secret: 'secret',  // Used to sign session id-related cookie s
    //store: new FileStore(), // Local Storage session (text files, or other stores, such as redis)
    saveUninitialized: false,  // Whether to automatically save uninitialized sessions, it is recommended that false
    resave: false,  // Whether to save the session every time, we recommend false
    cookie: {
        maxAge: 20*60 * 1000  // Validity period, in milliseconds
    }
}))

app.all
App. all is actually similar to app.get and app.post. It is a unified function of app.get and app.post, etc. It can receive any request. The path matches the complete path. If the match starts with a string, then add *. So app.all('*', (req, res, next) => {}) and app. use ((req, res, next) => {}) The effect is the same. But in general, in order to recognize and interpret program code, it is better to let it be executed semantically. One use of app.all is to handle cross-domain requests:

app.all('/*',(req,res,next)=>{
    res.header("Access-Control-Allow-Origin", "*");

    res.header("Access-Control-Allow-Methods","*");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

Posted by onyx on Sun, 11 Aug 2019 06:44:27 -0700