Introduction to Express:
Let's create an express application. Express is a node JS Web application framework, which is very powerful, can create various Web applications and HTTP tools for users, and use the express framework to build a fully functional website.
Advantages of Express framework:
Middleware can be used to respond to HTTP requests, routing tables can be defined to execute different HTTP requests, and parameters can be passed to the template to dynamically render html pages.
To install the Express framework from the command line:
cnpm install express --save
The Express framework is installed on the node_modules directory, and then the following modules need to be installed together:
Body parser is node JS middleware can handle JSON, raw, text and URL encoded data. Cookie parser is a middleware for parsing cookies, and then through req Cookies can get the cookies passed and turn them into objects.
multer is node JS middleware, which is used to process the form data of enctype = "multipart / form data".
cnpm install body-parser --save cnpm install cookie-parse --save cnpm install multer --save
Let's take a look at the version number of the express framework:
cnpm list express
Create the first Express framework instance
Purpose: to output: "hello", name: express_demo.js file
// Introducing node module const express = require('express'); // Create an express program const app = express(); // Add HTTP route app.get('/', function(request, response){ // Output response message response.send('hello express'); }); // Start HTTP server app.listen(8080, function(){ console.log('express app'); });
Project execution:
node express_demo.js
Then you can use http://127.0.0.1:8080
The express framework uses the request object and response object to process the data of the request and response:
app.get('/', function(req,res){ })
The request object is an HTTP request
req.app
For callback, call back the external file of the function, using req App access instance of express
req.baseUrl
Gets the URL path of the current installation
req.body/req.cookies
To get "request subject"
req.hostname/req.ip
Get host name and ip address
req.originalUrl
Get original request URL
req.params
Get parameters of route
req.path
Get request path
req.protocol
Get protocol type
req.query
Get query parameters of URL
req.route
Get the current matching express route
req.subdomains
Get subdomain name
req.accepts()
Check the document type that can accept the request
req.get()
Gets the specified HTTP request header
req.is()
Determine the Mime type of the content type of the request header
The response object is an HTTP response
res.app
For callback, call back the external file of the function, and use res.app to access the instance of express
res.append()
Append the specified HTTP request header
res.set()
Reset the previously set request header after res.append()
res.clearCookie()
Clear cookies
res.download()
Transfer files in the specified path
res.get()
Returns the specified HTTP request header
res.json()
Send json response
res.jsonp transfer jsonp response
res.location() only sets the location HTTP request header of the response, and does not set the status code or close response
res.redirect() sets the location HTTP request header of the response and sets the status code 302
res.send() sends HTTP response
res.status() sets the HTTP status code
res.type() sets the MIME type of content type
Guangzhou design companyhttps://www.houdianzi.com My 007 office resources websitehttps://www.wode007.com
express routing
express route is composed of URI, HTTP request and several handles.
// Introducing node module const express = require('express'); // Create an express program const app = express(); // Add http route app.get('/',function(request,response) { // Output response message response.send('hello dashucoding'); }); app.get('/users', function(req,res) { // req , res res.send('user'); }); // Start HTTP server app.listen(8080, function(){ console.lo('express app'); });
A GET request is a representation of a specified resource and is only used to obtain data
POST is used to submit the body to the specified resource
HEAD requests the same response as GET, but there is no response body
PUT is used to request the payload to replace all current representations of the target resource
DELETE deletes the specified resource
CONNECT establishes a tunnel for the server identified by the target resource
OPTIONS describes the communication OPTIONS of the target resource
PATCH is used to apply partial modifications to resources
app.get('/about',function(req,res){ res.send('about'); }); app.get('/ab?cd',function(req,res){ res.send('ab?cd'); } app.get('/ab(cd)?e',function(req,res){ res.send('ab(cd)?e'); });
Route handle, which provides multiple callback functions for request processing, and the next('route ') method
let d1 = function(req,res,next){ console.log('1'); next(); }; let d2 = function(req,res,next){ console.log('2'); next(); }); let d3 = function(req,res,next){ console.log('3'); next(); }); app.get('/', [d1,d2]);
Next is used to execute the next callback function, and next('route ') is used to execute the next same route.
// Introducing node module const express = require('express'); // Create an express program const app = express(); // Add http route app.get('/', function(request, response){ // Output response message response.send('hello'); }); app.get('/users', function(req,res){ res.send('user'); }); // dynamic app.get('/users/id', function(req,res){ let id = req.params.id; // Return response res.send('id='+id); }); // Start HTTP server app.listen(8080,function(){ console.log('expresss app'); }); const express = require('express'); const app = express(); app.get('/', function(request, response){ response.send('hello'); }); app.get('/users',function(req,res){ res.send('users'); }); app.param('id',(req,res,next)=>{ console.log('hello'); if(req.params.id==='1'){ next(); }else{ res.sendStatus(404); } }); app.get('/users/:id',(req,res)=>{ res.send('hello'); }); // Start server app.listen(8080,function(){ console.log('express'); });
pug view template
Command line download:
npm install pug
pug.compile() compiles the pug code into a JavaScript function.
app.js const express = require('express'); const app = express(); // Configure view template app.set('view engine', 'pug'); app.set('views', './views'); // Add HTTP route app.get('/', function(request, response){ response.render('index.pug'); // Output the response message, load and parse the index Pug file }); app.get('/users',function(req,res){ res.render('users.pug',{ title:'user', users:[ {id:1,name:'Zhang San',age:18} ] }); }); // Start HTTP server app.listen(8080,function(){ console.log('express'); });
users.pug:
doctype html html head meta(charset="utf-8") title #{title} body #app for user in users div p id=#{user.id} p name=#{user.name} p age=#{user.age} pug.render()Template function: const pug = require('pug'); console.log(pug.renderFile('template.pug',{ name:'dada' });
Execute pug Renderfile() function will automatically store the compiled function in the internal cache