Express Server Development

Posted by sticks464 on Tue, 17 Dec 2019 00:08:57 +0100

Author| Jeskson

Source|Dada Front End Bistro

Express Server Development

Create Express applications, Express routes, use of pug view templates

Introduction to Express:

Let's create Express applications, a Node.js Web application framework that is powerful enough to create a variety of Web applications and HTTP tools for users, and a fully functional Web site using the Express framework.

Advantages of the Express framework:

Middleware can be used to respond to HTTP requests, routing tables can be defined to perform different HTTP requests, and parameters can be passed to templates to dynamically render HTML pages.

Command line installation Express framework:

cnpm install express --save

The Express framework is installed in the node_modules directory, then the following modules need to be installed together:

body-parser is the middleware of node.js, which can process JSON, Raw, Text, and URL-encoded data. cookie-parser is an intermediate that parses cookies and then obtains the incoming Cookies through req.cookies and turns them into objects.

multer is the middleware of node.js that handles form data with enctype="multipart/form-data".

cnpm install body-parser --save
cnpm install cookie-parse --save
cnpm install multer --save

Let's look at the version number of the express framework:

cnpm list express

Create the first Express framework instance

Purpose For output:'hello', named: express_demo.js file

// Introducing a node module
const express = require('express');

// Create express program
const app = express();

// Add HTTP Routing
app.get('/', function(request, response){
 // Output response message
 response.send('hello express');
});

// Start HTTP Server
app.listen(8080, function(){
 console.log('express app');
});

Executing projects:

node express_demo.js

Then you can use it http://127.0.0.1:8080

The express framework uses request and response objects to process data for requests and responses:

app.get('/', function(req,res){
})

The request object is an HTTP request

req.app

For callback, callback function external file, use req.app to access an instance of express

req.baseUrl

Get the URL path for the current installation

req.body/req.cookies

To get the Request Body

req.hostname/req.ip

Get hostname, ip address

req.originalUrl

Get the original request URL

req.params

Get Route Parameters

req.path

Get Request Path

req.protocol

Get Protocol Type

req.query

Get query parameters for URL s

req.route

Get the currently matched express route

req.subdomains

Get Subdomain Name

req.accepts()

Check Document Types for Acceptable Requests

req.get()

Gets the specified HTTP request header

req.is()

Determine the Meme Type of the Request Header Content-Type

Response object is an HTTP response

res.app

For callback, callback function external file, Access express instance using res.app

res.append()

Append the specified HTTP request header

res.set()

Reset the previously set request header after res.append()

res.clearCookie()

Clear Cookie s

res.download()

Transfer files of specified path

res.get()

Returns the specified HTTP request header

res.json()

Send json response

res.jsonp Send jsonp response

res.location() Set only the Location HTTP request header for the response, not the status code or close response

res.redirect() Set the Location HTTP request header for the response and set the status code 302

res.send() Transfer HTTP response

res.status() Set HTTP status code

res.type() Set the MIME type of Content-Type

express routing

An express ion route consisting of a URI, HTTP request, and handles.

// Introducing a node module
const express = require('express');

// Create 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');
});

GET Request a representation of a specified resource for data acquisition only

POST Used to submit a corpse to a specified resource

HEAD Request the same response as GET, but no response body

PUT All current representations used to request a payload to replace the target resource

DELETE Delete the specified resource

CONNECT Set up a tunnel for the server identified by the target resource

OPTIONS Communication options for describing the target resource

PATCH 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');
});

Routing handle, providing multiple callback functions for request processing, 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 identical route.

// Introducing a node module
const express = require('express');
// Create 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 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 Routing
app.get('/', function(request, response){
response.render('index.pug');
// Output response message, load and parse 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'
});

Executing the pug.renderFile() function automatically stores the compiled function in the internal cache

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Topics: Front-end JSON npm Javascript PHP