node.js 21 express acquired parameters, template engine

Refer to the original article -http: //bjbsair.com/2020-03-22/tech-info/2823/
this morning to see a friend of mine asked me a message, now is not the popular koa2. Indeed, domestic use koa2 see a lot, but the whole global perspective, express usage is still high, and due to express occurred earlier, the whole ecosystem more complete, so it will have more of a long period of time user.

Personally approved data, just go to the website looked npm downloads of express and koa. Comparison chart below, freshly baked morning data.

node.js 11 express acquired parameters, template engine

VS express warriors

weekly downloads express reached 11.9 million weekly downloads koa is currently 410,000 . Although downloads contrast express dominant, but koa has its own advantages, the back of my article will be devoted koa. Practical work, on the one hand we need to use mature and stable technology, but can not relax knowledge of new technologies, new things, otherwise it will soon be thrown in this era of rapid development. IT people need to live to old to learn of.

Next, return to this chapter need to introduce.

express parameter acquisition

The argument here is divided into several categories, one is the information entered by the user in the form of web pages, one is in the url path information, as well as the post is how to obtain parameters.

  1. Access to information entered by the user in the form of web pages

If the form used is the GET method, the form information will be passed to the following form in the url.

http://localhost:3000/create?name=Vincent&age=18

Form in this example there are two elements, namely name and age. Submitting, parameters are added in such a form is sent to the server after the url.

Again, the framework needs to provide packaging for native function, as far as possible so that users quick and easy to use features. After express, the web form to submit data to the server, the data in the form of key-value pairs stored in request.query object. ** acquiring parameter values, to just use request.query **, examples are as follows:

let name = request.query.name;

I suppose the "name" text box enter a value Vincent browser, then the above code will be able to get to "Vincent".

Compared to node.js native method to obtain parameters, express a lot of convenience. node.js native form parameter acquisition method need to be manually introduced into the url package, after the parse by, after obtaining the parameter values ​​in the call query.

  1. The acquisition parameters url path

With the popularity of rest of the way, when you call the rest api, the parameter value will be placed directly in the path url. Example, suppose that we need to get more information through the user's user name, then you can use the following url

 http://localhost:3000/user/Vincent

In app.js service side, we must first add the following routing "/ user /: name". Then get argument by request.params pairs. And form inside the parameters of preservation is not the same, path of the parameters are stored in request.params in.

app.get('/user/:name', function userIdHandler (req, res) {  
  console.log(req.params)  
})

So we can see the following key information, name of the console in the object request.params in.

{ name: 'Vincent' }  
GET /user/Vincent 200 16.076 ms - 13

If we wish to pass multiple parameters, you can continue to add parameters after the path.

 http://localhost:3000/user/Vincent/age/18

Add Route "/ user /: name / age: age" in app.js in.

app.use('/user/:name/age/:age',function(req, res, next) {  
  console.log(req.params);  
  res.send("name: " + req.params.name + ",  age: " + req.params.age);  
});

This is the console output there will be more of age of pairs.

{ name: 'Vincent', age: '18' }  
GET /user/Vincent/age/18 304 3.396 ms - -

Page displayed in Figure

node.js 11 express acquired parameters, template engine

path parameter passing

  1. POST method parameter passing

In the first point in the form of the GET method when we use mass participation, which is a parameter stored in request.query in. If the parameter passing the POST method, parameters are stored in the request.body.

In app.js, the use app.js still call the relevant router , router name we use the assumption here is createRouter.

app.use('/create', createRouter);

In createRouter corresponding js file using router.post () method .

router.post('/', function(req, res, next) {  
  console.log("----------------------------------------------")  
  console.log(req.body)  
  console.log("----------------------------------------------")  
});

After the run, we can see the console req.body of this object, which the information is stored in the form of key-value pairs.

----------------------------------------------  
[Object: null prototype] {  
  name: 'Vincent',  
  age: '18'  
}  
----------------------------------------------

express template engine

java web applications will use a jsp view, early applications directly by adding servlet html template way, then like now Spring + thymeleaf. Of course, now the front-end technology has been rapidly changing, and a variety of front-end frame after another. As a web framework is concerned, there will be associated with the front end of the function, otherwise not well used and promoted.

express support multiple default template engine. After you install the express generator (can refer to my previous express describes the installation), just enter the command line "express -h" you can see all the parameters of the option.

D:\Projects\nodejs\NodeDemo\forms>express -h  
  Usage: express [options] [dir]  
  Options:  
        --version        output the version number  
    -e, --ejs            add ejs engine support  
        --pug            add pug engine support  
        --hbs            add handlebars engine support  
    -H, --hogan          add hogan.js engine support  
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)  
        --no-view        use static html instead of view engine  
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)  
        --git            add .gitignore  
    -f, --force          force on non-empty directory  
    -h, --help           output usage information

In here, we can see the default template engine jade, in addition to jade, also supports the dust | ejs | hbs | hjs | jade | pug | twig | vash and other template engines.

When you run the command "express" create a project file, use the default engine in app.js it is jade.

// view engine setup  
app.set('views', path.join(__dirname, 'views'));  
app.set('view engine', 'jade');

If you need to use other engines instead of jade, such as ejs, you can use the "express -e" command when creating the project.

If the project has been created, the engine will be switched to "ejs", you can still use the above command.

D:\Projects\nodejs\NodeDemo\node10>express -e  
  warning: option `--ejs' has been renamed to `--view=ejs'  
destination is not empty, continue? [y/N] y  
   create : public\  
   create : public\javascripts\  
   create : public\images\  
   create : public\stylesheets\  
   create : public\stylesheets\style.css  
   create : routes\  
   create : routes\index.js  
   create : routes\\users.js  
   create : views\  
   create : views\error.ejs  
   create : views\index.ejs  
   create : app.js  
   create : package.json  
   create : bin\  
   create : bin\www

Meanwhile, the command also app.js settings engine code changes.

app.set('view engine', 'ejs');

This is not enough, you need to install ejs in the current project directory in subsequent runs.

D:\Projects\nodejs\NodeDemo\node10>npm install ejs --save  
+ [email protected]  
added 1 package from 2 contributors, removed 47 packages and audited 141 packages in 3.64s  
found 0 vulnerabilities

Personal selection ejs, since substantially the same with the wording jsp variables in ejs, using <% = variable%> form.

 <body>  
    <h1><%= title %></h1>  
    <p>Welcome to <%= title %></p>  
  </body>

In use, you will only need to pass the value of the variable in the router.

router.get('/', function(req, res, next) {  
  res.render('index', { title: 'Express' });  
});

The code above in "index" index represents the use of templates, that /views/index.ejs. {Title: 'Express'} represent variables used by the template. After passed, the alternative index.ejs <% = title%>, the resulting page is as follows.

node.js 11 express acquired parameters, template engine

ejs

to sum up

express acquired parameters in three ways, the template engine to use and set first introduced here. Hope Benpian allows you to get help when using the express.

If you have questions, comments welcome friends to discuss.

Original articles published 0 · won praise 0 · Views 297

Guess you like

Origin blog.csdn.net/zxjoke/article/details/105084946