Express method
Express is a concise and flexible node. JS Web application Development Framework and is currently the most popular node. JS-based Web development framework. It offers a range of powerful features, such as:
Template parsing
Static file Service
Middleware
Routing control
Use Express in node to create an HTTP request with the following steps:
1, Introduction of Express module
2, execute Express method
After the 3,express method executes, it returns an HTTP listener function that can listen to the port using the returned function.
Request static resources by using middleware
Express Building Services
let express=require("express");let app=express();app.listen(8080);
After the Express function executes, an HTTP listener function is returned, which is the function in Http.createserver
On this function, a listen is extended to listen to the port, and App.listen is based on the previously encapsulated
app.listen=function (...arg) { require("http").createServer(app).listen(...arg)}app.listen(8080,()=>{ "8080端口已开启"})
Express-based listener functions extend a lot of methods to express routing
The method and path are all matched to perform the corresponding callback
1. In the process request path and mode, indicates the way of the request, including the Get post delete put,restful style verbs, compared with the previous do not need to be judged
app.get("/sigin",function (req,res) { res.setHeader("content-type","text/plain;charset=utf-8"); res.end("登录");});app.post("/sigin",function (req,res) { res.setHeader("content-type","text/plain;charset=utf-8"); res.end("post登录");});//all表示所有的方法,*表示所有的路径,一般放到最后app.all("*",function (req,res) { res.end("404")})
Returns the login if Localhost:8080/sigin is requested
Parameter routing:
For the same path in the path, we can distinguish one or more content by routing parameters, all the route parameters are placed in the Req.params object,
app.get("/user",function (req,res) { res.end("select all")});app.get("/user/:id/:name",function (req,res) { res.end("select one"+req.params.id+req.params.name);});
2. If you want to get the path parameter of the request can be obtained using the App.params () method, this method has interception function, only after calling the next () method to continue to go down
app.param("id",function (req,res,next) { req.params.id=`你的学号是${req.params.id}`; //res.end("123") next();//调用了next就可以向下匹配,如果在这里结束了请求那就不走了});app.param("name",function (req,res,next) { req.params.name=`你的名字是${req.params.name}`; next();})app.get("/user/:id/:name",function (req,res) { res.header("content-type","text/plain;charset=utf-8"); res.end("select one"+req.params.id+req.params.name);});
Response Successful return content: Select one your school number is 1 your name is MD
Middle Key
To do something before accessing the final target, then the App.use () method can
App.use ()
1) function
1. Permissions can be judged
2. The properties of RES and req can be expanded
3 The middle key is placed above the path to be executed
4 The middle key is matched by default, and you can specify what the beginning of the match
2) Use
If we want to do something, we can also use the middleware before matching the route and returning the data
app.use(function (req,res,next) {//不调用next就不继续往下走 console.log("过滤石头"); req.stone="too big"; res.end("hello"); next(); // next("错误");});app.use(function (req,res,next) {//不调用next就不继续往下走 console.log("过滤沙子"); req.sand="too small"; next();});app.get("/foot",function (req,res) { console.log(req.stone,req.sand); res.end("foot");})app.get("/water",function (req,res) { console.log(req.stone,req.sand); res.end("water");});app.use(function (err,req,res,next) { console.log(err); next();})
If Next () passes the parameter, the middle key goes with the method that has four parameters, that is, the last method
3) Method Encapsulation principle
function app() { //每次调用use方法都会将方法存到数组中,默认调用数组的第一项,将next方法传递给数组中的函数,如果调用次函数 会继续执行数组中的下一项 app.middlereware=[];}app.use=function (cb) { this.middlereware.push(cb);};app.use(function (res,req,next) { console.log(1); next();});app.use(function (res,req,next) { console.log(2); next();});app.use(function (res,req,next) { console.log(3);});let index=0;function next() { app.middlereware[index++](null,null,next);};next();
Extends some of the properties and methods in the Res,req
1) Extended properties and methods on req
Req.query.id Getting route parameters
Req.path Get Path
let express=require("express");let app=express();app.listen(8081);app.get("/user",function (req,res) { console.log(req.query.id);//express扩展的属性 console.log(req.url);//获取整个路径包括问号 console.log(req.path);//express扩展的属性 console.log(req.headers);//所有的都是小写 console.log(req.method);//所有的方法都是大写})
2) Extended properties and methods on Res
1,res,json (), returns the string returned in JSON format directly
The data returned by the previous response needs to be converted through json.stringfly () before it can be returned
app.get("/json",function (req,res) { res.json({name:"你好",age:8});//响应json});
2, previously returned a paging file to be read through FS, can now be obtained through the Res.sendfile () method, the path must be an absolute path
app.get("/",function (req,res) { // res.sendFile("./index.html",{root:__dirname});不能通过../查找(root是不支持的)想读取到确切的文件 用path模块进行拼接即可 res.sendFile(require("path").join(__dirname,"..","index.html"))});
3. Return status code does not need to pass Res.setstatecode (), can use Res.send (), can also return Chinese, do not need to set the response header type, can automatically set the returned response header type according to the returned data type
app.get("/send",function (req,res) { // res.send("中文") res.send(200)});
Encapsulation of the Send () method
app.use(function (req,res,next) { res.mySend = function (data) { if(typeof data === ‘object‘){ res.setHeader(‘Content-Type‘,‘application/json;charset=utf8‘); return res.end(JSON.stringify(data)); } if(typeof data === ‘string‘){ res.setHeader(‘Content-Type‘,‘text/plain;charset=utf8‘); return res.end(data); } if(typeof data === ‘number‘){ res.statusCode = data; res.end(require(‘_http_server‘).STATUS_CODES[data]); } }; next();});app.get(‘/send‘,function (req,res) { res.mySend(500);}
Route split (set level two routing) to get Dynamic Data
Express can be passed through Express. Router () and middleware settings child routing All Zi Lu are placed under a routes folder, the folder can be placed in multiple identical modules, each module needs to introduce the Express module, set the path of the sub-route and the corresponding method, and export the module moudle.export={}, and then reference the routes file clip module in the main module, through the Require, and then through the middleware use () method, matching level two routing
let express = require(‘express‘);let app = express();let router = express.Router();router.get(‘/login‘,fn)app.use(‘/user‘,router);
Bodyparser
app.use(bodyParser.json()); // 解析json application/jsonapp.use(bodyParser.urlencoded({extented:true})); // 解析表单 application/x-www-form-urlencoded
Ejs usage
<!--引入模板--><%include header.html%><!--取值-->
Ejs template renders the file by default is a file with the Ejs suffix, and is placed in the current directory of the View folder, and when you get the data to render the data through the render function, the rendered template file is with the Ejs suffix, you can use the middleware to change the suffix of the template file to HTML, Change the name of the view folder to a static file
//更改默认模板的后缀app.engine(‘html‘,require(‘ejs‘).__express);// 更改模板路径,默认叫viewsapp.set(‘views‘,‘static‘);// 配置默认模板后缀名字app.set(‘view engine‘,‘html‘);
Static service MiddlewareRequest a file file by Express.static ()
app.use(express.static(‘文件夹‘))
redirectres.redirect(‘路径‘);
This allows us to build an express-based HTTP, service, via Express. Router (), constructs the child route, obtains and responds the data, through the Express.static () method may request the static resource, through the App.use () The request routing, the data, the response data carries on the processing, thus enhances the entire HHTP request the controllability
Express build HTTP service, get static files and dynamic data through routing and middleware implementation principle