Nodejs Foundation (iii)

Source: Internet
Author: User

I. Express FRAMEWORK

The Express framework is the node frame behind the scenes, so it's not a thing with jquery, Zepto, Yui, Bootstrap.

The popularity of express in the background, like jquery, is the de facto standard of business.

Native node development, you will find a lot of problems. Like what:

Presenting a static page is inconvenient, you need to handle each HTTP request, and consider 304 issues

The route processing code is not intuitive and requires a lot of regular expressions and string functions to be written

Can't concentrate on writing business, there are many other things to consider

We can ourselves put the first day's work, that is, the static file service to the package as a module. The more you encapsulate, the more you make something like Express.

The philosophy of Express is to act as a thin layer between your idea and the server. This does not mean that he is not strong enough, or does not have enough useful features, but tries to intervene as little as possible, allowing you to fully express your thoughts while providing something useful.

English official website: http://expressjs.com/

Chinese Civil Service Network: http://www.expressjs.com.cn/

Overall perception, express framework.

Installing the Express framework is the use of NPM commands.

1 npm Install --save Express

The--save parameter, which indicates that the Package.json file is automatically modified and the dependencies are added automatically.

Routing capabilities:

1 var express = require ("Express");

2

3 var app = Express ();

4

5 App.get ("/", function (req,res) {

6 res.send ("Hello");

7});

8

9 App.get ("/haha", function (req,res) {

Ten Res.send ("This is the haha page, haha haha haha");

11});

12

App.get (/^\/student\/([\d]{10}) $/,function (req,res) {

Res.send ("Student information, study number" + req.params[0]);

15});

16

App.get ("/teacher/:gonghao", function (req,res) {

Res.send ("Teacher information, work number" + Req.params.gonghao);

19});

20

App.listen (3000);

Static file servo capability:

1 App.use (Express.static ("./public"));

Template engine:

1 var express = require ("Express");

2

3 var app = Express ();

4

5 App.set ("View Engine", "Ejs");

6

7 App.get ("/", function (req,res) {

8 Res.render ("haha", {

9 "News": ["I am a little news ah", "I also ah", "haha haha"]

10});

11});

12

App.listen (3000);

express4.x, and express3.x very big difference. Second, the route

What to do when accessing a URL with GET request:

1 app.get ("url", function (req,res) {

2

3});

When you use post to access a URL, do something:

1 app.post ("url", function (req,res) {

2

3});

If you want to process the request for any method of this URL, then write all

1 App.all ("/", function () {

2

3});

Here's the URL, no case, that is, your route is

1 App.get ("/aab", function (req,res) {

2 res.send ("Hello");

3});

Actually, lowercase access is also OK.

All the get parameters,? The following are ignored. Anchor # is also ignored.

You route to/A, the actual/a?id=2&sex=nan can also be processed.

Regular expressions can be used. In regular expressions, the unknown part is grouped by parentheses, which can then be obtained using req.params[0], [1].

The Req.params class array object.

1 App.get (/^\/student\/([\d]{10}) $/, function (req,res) {

2 res.send ("Student information, study number" + req.params[0]);

3});

The colon is a more recommended notation.

1 App.get ("/student/:id", function (req,res) {

2 var id = req.params["id"];

3 var reg=/^[\d]{6}$/; Regular validation

4 if (Reg.test (ID)) {

5 res.send (ID);

6}else{

7 Res.send ("Please check format");

8}

9});

Forms can be submitted on their own.

1 App.get ("/", function (req,res) {

2 Res.render ("form");

3});

4

5 App.post ("/", function (req,res) {

6//Add data into the database

7 Res.send ("Success");

8});

Suitable for restful routing designs. Simply put, is a path, but the HTTP method is different, the use of this page is different.

/student/345345

Get Read Student information

Add Student Information

Delete Remove students new third, middleware

If there is no next parameter in my get, post callback function, then it will match the first route and it will not match down.

If you want to match down, then you need to write next ()

1 App.get ("/", Function (Req,res,next) {

2 Console.log ("1");

3 next ();

4});

5

6 App.get ("/", function (req,res) {

7 Console.log ("2");

8});

The following two routes, feel no relationship:

1 App.get ("/:username/:id", function (req,res) {

2 Console.log ("1");

3 Res.send ("User Information" + req.params.username);

4});

5

6 App.get ("/admin/login", function (req,res) {

7 Console.log ("2");

8 res.send ("admin login");

9});

But in fact conflict, because admin can be as user name login can be used as ID.

Solution 1: Swap the location. In other words, the order of all the routes (middleware) in Express is critical.

Match on the first one, it will not match down. Write on the concrete, and write down the abstract.

1 App.get ("/admin/login", function (req,res) {

2 Console.log ("2");

3 res.send ("admin login");

4});

5

6 App.get ("/:username/:id", function (req,res) {

7 Console.log ("1");

8 Res.send ("User Information" + req.params.username);

9});

Workaround 2:

1 App.get ("/:username/:id", Function (Req,res,next) {

2 var username = Req.params.username;

3//Retrieve database, if username does not exist, then next ()

4 if (retrieve database) {

5 Console.log ("1");

6 Res.send ("User Information");

7}else{

8 next ();

3 ·

10});

11

App.get ("/admin/login", function (req,res) {

Console.log ("2");

Res.send ("Administrator Login");

15});

Routing get, post these things, is the middleware, the middleware order, matching on the first after the match will not be back. Next function can continue to match later.

App.use () is also a middleware. Unlike get, post, his URLs are not exactly matched. It can be expanded with small folders.

For example URL: http://127.0.0.1:3000/admin/aa/bb/cc/dd

1 App.use ("/admin", function (req,res) {

2 Res.write (Req.originalurl + "\ n"); /admin/aa/bb/cc/dd

3 Res.write (Req.baseurl + "\ n"); /admin

4 Res.write (Req.path + "\ n"); /aa/bb/cc/dd

5 res.end ("Hello");

6});

If you write A/

1//When you do not write the path, it is actually the equivalent of "/", that is, all the URLs

2 App.use (function (req,res,next) {

3 Console.log (New Date ());

4 Next ();

5});

App.use () gives us a convenient place to add some specific features.

actually App.use () is basically something that can be obtained from a third party.

In most cases, the rendered content is Res.render () and will be rendered according to the template file in the views. If you do not want to use the Views folder, you want to set the folder name, then App.set ("views", "AAAA");

If you want to write a quick test page, of course you can use Res.send (). This function will automatically help us set the Content-type header and 200 status code based on the content. Send () can only be used once, as with end. It's not like end. Ability to set MIME types automatically.

If you want to use a different status code, you can:

Res.status (404). Send (' Sorry, we cannot find that! ');

If you want to use a different content-type, you can:

Res.set (' Content-type ', ' text/html ');


Iv. parameters for GET requests and post requests

The parameters of the GET request are in the URL, and in native node, the URL module is used to identify the parameter string. In Express, there is no need to use the URL module. You can use the Req.query object directly.

Post requests are not directly available in Express and must use the Body-parser module. After use, the parameters can be obtained with req.body. However, if the form contains file uploads, you still need to use the formidable module.

Node is full of callback functions, so we encapsulate our own function, if there are asynchronous methods, such as I/O, then the callback function is used to encapsulate the method.

Error:

1 res.reder ("index", {

2 "name": Student.getdetailbyid (234234). Name

3});

4

5

That's right:

6

7 Student.getdetailbyxuehao (234234,function (detail) {

8 Res.render ("index", {

9 "name": detail. Name

10})

11});

12

1

Nodejs Foundation (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.