22.Express Framework - December 19, 2019

December 19, 2019 14:16:36

1. express Profile

1.1 Introduction

Express framework Node frame background, and so jQuery, zepto, yui, bootstrap not a thing.

The popularity of Express in the background, and jQuery, as is the de facto corporate standard.

Native Node development, you will find a lot of problems. such as:

■ presenting static pages inconvenient to deal with each HTTP request, but also consider issues 304

■ routing processing code is not intuitively clear, the need to write a lot of regular expressions and string functions

■ You can not concentrate on writing business, a lot of other things to consider

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

Chinese official website: http://www.expressjs.com.cn/

Express installation frame, is to use the command npm.

--save parameter that indicates automatically modify package.json file, automatically add dependencies.

1.2 The concept of middleware

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.

1.2.1 app.use()

app.use([path],function)

path: url is the route, the default parameters '/', meaning the use of this intermediate to the routing path

function: function middleware

This function can be understood as the middleware isfunction(request,response,next)

1.2.2 Built-in middleware

express.static `Express is the only built-in middleware. Serve static resource files.

app.use(express.static(__dirname + '/public'));

Start Service: node index.js

Browser access: HTTP: // localhost: 1234 / show content /public/index.html

Browser access: HTTP: // localhost: 1234 / hello.html show /public/hello.html content

1.2.3 How to customize the middleware

In the above structure middleware, we know that the second argument when using the middleware is a Function, however, a custom middleware, and shift some of this is Function.

There are three parameters of this function (req, res, next)

When each request arrives at the server, nodejs will create a request object request (request), the request object contains data submitted by the client up. But also create a response object (response), the response object is responsible for the response data server to the client. The last parameter is a next method, because an application can use multiple middleware, and in order to run a middleware, a middleware must then run next ().

1.2.4 third-party middleware

About third-party middleware, here we analyze some of the more important and commonly used, few know that the use of other'll get it.

body-parser: Parsing the body data, and save it as the Request object body property.

cookie-parser : Parsing data from the client in a cookie and save it as a cookie property of the Request object

express-session : Parsing the server generated sessionid corresponding session data, and saved as session attribute Request object

query: This middleware will convert from a URL query string to JS objects, and save it as a query property Request object. This middleware in the fourth version has been built without installation.

2. Routing

2.1 app.get()

res.send()

res.render()

app.listen()

app.get("/",function(req,res){

res.send("hello");

});

var express = require("express");
var app = express();

app.get("/",function(req,res){
    res.send("你好");
});

app.get("/haha",function(req,res){
   res.send("这是haha页面,哈哈哈哈哈哈");
});

app.get(/^\/student\/([\d]{10})$/,function(req,res){
    res.send("学生信息,学号" + req.params[0]);
});

app.get("/teacher/:gonghao",function(req,res){
    res.send("老师信息,工号" + req.params.gonghao);
});
app.listen(3000);

2.2 get access URL

When a get request to access a Web site, do something:

app.get("网址",function(req,res){

});

If you want to request any method of dealing with this web site, then write all

app.all("/",function(){
    
});

note:

All GET parameters? Back have been ignored. # Anchor also ignored

You are routed to / a, actual / a? Id = 2 & sex = nan also be processed.

2.3 regular expressions, get get parameters

Regular expressions can be used. Regular expression, unknown parts in parentheses packets, can then be req.params [0], [1] obtained.

Colon is more recommended wording.

app.get("/student/:id",function(req,res){
    var id = req.params["id"];
    var reg= /^[\d]{6}$/;   //正则验证
    if(reg.test(id)){
       res.send(id);
    }else{
        res.send("请检查格式");
    }
});

2.4 acquisition parameters

//冒号
app.get("/:username/:oid",function(req,res){
    var username = req.params["username"];
    var oid = req.params["oid"];

    res.write(username);
    res.end(oid);
});

app.listen(3000);

2.5 Processing Get, Post request parameters

GET request parameter in the URL, the primary Node, it is necessary to identify the module using the url parameter string.

In Express, without the url of the module. It can be used directly req.query object.

app.get("/",function(req,res){
    console.log(req.query);
    res.send();
});

POST requests can not be obtained directly express, it is necessary to use body-parser module. After use, the parameters can be obtained req.body.

But if the form contains file upload, you still need to use the formidable modules.

var bodyParser = require('body-parser')

//模板引擎
app.set("view engine","ejs");

app.get("/",function(req,res){
     res.render("form");
});

//bodyParser API
app.use(bodyParser.urlencoded({ extended: false }))

app.post("/",function(req,res){
    console.log(req.body);
});

3. Static file access

app.use(express.static("./public"));

app.set()

app.use()

4. The template engine

4.1 ejs

Use a template engine ejs

app.set("viwe engine","ejs");

var express = require("express");

var app = express();

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

app.get("/",function(req,res){
    res.render("haha",{
        "news" : ["我是小新闻啊","我也是啊","哈哈哈哈"]
    });
});

app.listen(3000);

Note: express4.X and express3.X the difference is very large.

4.2 Data transfer app.render (view, [locals], callback)

app.get("/",function(req,res){
    res.render("haha",{
       "news" : ["我是小新闻啊","我也是啊","哈哈哈哈"]
    });
});

5. Middleware

5.1 next parameter

If you get, post callback function, there is no next argument, then the first one that matches the route, it will not match up down.

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

app.get("/",function(req,res,next){
    console.log("1");
    next();
});

app.get("/",function(req,res){
    console.log("2");
});

After routing get, post these things, that is middleware, middleware pay attention to the order's first match, the match will not be back. The next function to be able to continue to the next match.

5.2 use () action

app.use () is a middleware. And get, post different is that he's not an exact match of the URL. But is capable of a small folder to expand.

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

app.use("/admin",function(req,res){ 
    res.write(req.originalUrl + "\n");   //    /admin/aa/bb/cc/dd
    res.write(req.baseUrl + "\n");  //   /admin
    res.write(req.path + "\n");   //    /aa/bb/cc/dd
    res.end("你好");
});

Static service

//静态服务
app.use("/jingtai",express.static("./public"));

6. Content Rendering

● In most cases, rendering content with res.render (), will be rendered according to the template file views in. If you do not want to use the folder views, you want to set up their own folder name, then

app.set("view engine","ejs")

● If you want to write a quick test page, of course, you can use res.send (). This function will be based on content, automatically help us set the Content-Type header and 200 status code.

send () can only be used once, and end the same. And where the end is not the same? MIME type can be automatically set.

● 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 different Content-Type, you can:

res.set('Content-Type', 'text/html');

Modify the point in time:

October 5, 2019 12:26:16

Guess you like

Origin www.cnblogs.com/oneapple/p/12067701.html