Introduction to the Node. js lightweight Web framework Express4.x User Guide, node. jsexpress4.x

Source: Internet
Author: User
Tags set cookie subdomain name

Introduction to the Node. js lightweight Web framework Express4.x User Guide, node. jsexpress4.x

Express is a lightweight Web framework that is simple and flexible

It is also the most popular Nodejs-based Web framework.

With this feature, we can quickly build a complete website (express)

Express is now in version 4.x, which is updated quickly and is not compatible with earlier versions. As a result, many excellent Node books on the market are outdated.

This article is an entry-level Express application that requires the foundation of Node. js.

Web application Creation

The first thing to do is to download and reference express

npm install express --save

+-G for global installation

Reference express

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

Through the app, we can use various express APIs

In version 3.x, it is written in this way.

var app =express.createServer(); 

Now this function has been abandoned.

Create an application

//app.jsvar express = require('express');var app = express();app.get('/', function(req, res){ res.send('Express');});app.listen(3000);

After startup, you can see the effect on the page.

$ node app.js

App. get ()

The above app. listen () won't be said much.

Listener Port

app.get(path, function(req, res){ }) 

Used to process GET requests sent from a client to a server

Path indicates the Request path.

The req and res of the callback function are the meaning of request and response.

Request indicates the HTTP request information sent by the client.

Response indicates the HTTP response Message sent by the server

Use res. send () to send messages to the client.

//app.jsvar express = require('express');var app = express();app.get('/', function(req, res){ res.send(' 

App. post ()

app.post(path, function(req, res){ }) 

Used to process POST requests sent from clients to servers

Unlike GET requests, POST requests do not place information in URLs.

It is written into the request header.

Its resolution is different. Let's talk about it later.

App. all ()

A concept-Middleware

Middleware has different meanings in different environments

In our express, it is simply a special function.

Functions used to process HTTP requests

And it has a feature: After processing a middleware, it can be passed to the next middleware for processing.

funciton(req, res, next){  ...  next();}

(If you do not use the next function, the function to be listened to will not be executed)

The string parameter can be passed to next to indicate the error message thrown.

In this way, the middleware will not process the data when it passes down.

Until an error handling function is found.

Inapp.all(path, function(req, res, next){ })In use

We need to define such middleware.

This method can filter requests in all paths.

In other words, before all other middleware Processes

It must be processed through the app. all () middleware.

var express = require('express');var app = express();app.all('*', function(req, res, next){ res.writeHead(200, ':)'); next();});app.get('/', function(req, res){ res.end('

In this way, no matter what path request the client sends to us

The response header is added before the server responds to the information.

App. use ()

app.use([path, ]function(req, res, next){ }) 

This method is generally used to call the middleware.

Unlike the previous function, the first path parameter can be omitted. The default value is '/'

app.use(express.static(path.join(__dirname, '/public')));

The above usage is to specify the access path of the static file

Using the next parameter, we can call the middleware function continuously.

app.use(function(req, res, next){ console.log(1); next();});app.use(function(req, res, next){ console.log(2); next();});app.use(function(req, res, next){ console.log(3);});app.use(function(req, res, next){ console.log(4);});

When a network request is sent

The console will output 1 2 3

Because the third middleware did not call the next Method

So far

No output 4

In addition to calling middleware, app. use ()

You can also return different information based on different request paths.

But we generally won't use it like this.

//app.jsvar express = require('express');var app = express();app.use(function(req, res, next){ if(req.url == '/'){  res.end('

Request and response

Req and res parameters are indispensable for each callback function in express above.

The importance is evident.

Common attributes/methods in req and res are as follows (req and res attributes/methods of native node. js can also be used)

Request object:

API Description
Req. app When callback is an external file, it is used to access the express instance.
Req. baseUrl Obtain the URL path of the route currently installed
Req. body/cookies Obtain request subject/Cookies
Req. fresh/stale Determine whether the request is "fresh 」
Req. hostname/ip Get host name and IP address
Req. originalUrl Get original request URL
Req. params Obtain the parameters of a route
Req. path GET Request Path
Req. protocol Obtain protocol type
Req. query Obtain the URL query parameter string
Req. route Obtain the current matched route
Req. subdomains Retrieve subdomain name
Req. acceptsCharsets Returns the first accepted character encoding of the specified character set.
Req. acceptsEncodings Returns the first accepted character encoding of the specified character set.
Req. acceptsLanguages Returns the first accepted character encoding of the specified character set.
Req. accepts () Check document types of accepted requests
Req. get () Obtains the specified HTTP request header.
Req. is () Determine the MIME Type of the Request Header Content-Type

Response object:

API Description
Res. app Same as req. app
Res. append () Append the specified HTTP Header
Res. set () After res. append (), the previously set header is reset.
Res. cookie () Set Cookie
Res. clearCookie () Clear Cookie
Res. download () Transfer the file in the specified path
Res. get () Returns the specified HTTP header.
Res. json () Send JSON response
Res. jsonp () Send JSONP response
Res. location () Only the Location HTTP header of the response is set, and the status code or close response is not set.
Res. redirect () Set the Location HTTP header for the response and the status code 302
Res. send () Send HTTP Response
Res. sendFile () Transfer the file in the specified path-Content-Type is automatically set based on the file extension
Res. set () Set the HTTP header. You can set multiple headers at a time when an object is imported.
Res. status () Set HTTP status code
Res. type () Set the MIME Type of Content-Type

Pick key points

Req. query

Req. query can obtain the object of the Request Path parameter.

Send the http: // localhost: 3000/? request to the server /? User = tester & pass [a] = 123 & pass [B] = 456

//app.jsvar express = require('express');var app = express();app.get('/', function(req, res, next){ console.log(req.query); console.log(req.query.user); //tester console.log(req.query.pass.a); //123 console.log(req.query.pass.b); //456 res.end();});app.listen(3000);

Req. params

Req. params can parse attributes on complex routing rules.
(Req. param integrates the functions of req. query and req. param, but is removed. Do not use it)

Send the http: // localhost: 3000/123456 request to the server

//app.jsvar express = require('express');var app = express();app.get('/:id', function(req, res, next){ console.log(req.params.id); //123456 res.end();});app.listen(3000);

In this way, no matter what I enter after the root path

Will be parsed as req. params. id

Res. send ()

Res. send is used to respond to the client. Its strength lies in its ability to intelligently process different types of parameters we pass.

app.get('/', function(req, res, next){ res.send('express');});

When the parameter is a string, the response header Content-Type is set to text/html by default.

That is, parse to html and render it on our page.

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

When the parameter is a number, it will automatically help us set the response body (Status Code ...)

app.get('/', function(req, res){ res.send([1, 2, 3]);});

When the parameter is an array or object, it returns a JSON

Res. redirect ()

This method allows us to redirect webpages.

For example, you can use an absolute url to jump to a different domain name.

app.get('/', function(req, res){ res.redirect('http://www.baidu.com');});

Res. redirect () the default response status code is 302.

You can change this status code as the first parameter of res. redirect ().

//app.jsvar express = require('express');var app = express();app.get('/', function(req, res){ res.redirect(302, 'demo');});app.get('/demo', function(req, res){ res.end();});app.listen(3000);

In the url address bar, enter http: // localhost: 3000

The page will be redirected to http: // localhost: 3000/demo

Static Resources

Static resources refer to the css, js, img, and so on used in development.

They need to be stored in a static resource directory.

When the browser sends a non-HTML file request

The server will find the file from the static resource directory.

We generally create a public file in the root directory to store

Create stylesheets, javascripts, images, and other folders in public.

Used to store specific types of resources

The method for specifying the static resource directory has been mentioned above

var path = require('path');app.use(express.static(path.join(__dirname, 'public')));

For example, we have such code in html.

<link href="/javascripts/jquery.js" rel="external nofollow" rel="stylesheet" media="screen">

Then the client runs and sends a request

The server will find the jQuery. js static resource in the public javascripts folder.

Template engine

By default, the express framework is an ejs and jade rendering template.

Jade is used as an example.

Must be downloaded during use

npm install jade --save

Then, use app. set () to specify the directory of the template file (similar to static resources)

And specify the template file suffix as jade

app.set('views', path.join(__dirname, 'views'));app.set('view engine', 'jade');

(If you do not use a template, use native html, app. set ('view engine ', 'html ');)

What should we do if we want to access the template?

Very simple. You only need a method res. render ()

Now I have written a simple jade template (the jade syntax is beyond the scope of this article)

//views/index.jadedoctype htmlhtml head  title= title  link(rel='stylesheet', href='/stylesheets/style.css') body  h1= title  p= content

Rendering through res. render

//app.jsvar express = require('express');var path = require('path');var app = express();app.use(express.static(path.join(__dirname, 'public')));app.set('views', path.join(__dirname, 'views'));app.set('view engine', 'jade');app.get('/', function(req, res){ res.render('index', {  title: 'Express',  content: 'this is an example' });});app.listen(3000);

Res. render ()

res.render(view[, datas][, callback])

Used to render webpage templates

The first parameter is the name of the template to be rendered.

The second parameter is the variable passed to the template. It is stored as an object and cannot be omitted.

The third parameter is the callback function after rendering, which can be omitted

Routing

Routing means specifying different processing methods based on different paths.

We generally encapsulate different routes into different modules.

First, create a folder routes storage route under the root directory

Now I create two routing files in the routes Folder: index. js and users. js.

Modify app. js

//app.jsvar express = require('express');var path = require('path');var app = express();var index = require('./routes/index');var users = require('./routes/users');app.use('/', index);app.use('/users', users);app.listen(3000);

This indicates that the route for http: // localhost: 3000/is handed over to the index for processing.

Http: // localhost: 3000/users route to users for processing

Below is a simple implementation of the routing

//routes/index.jsvar express = require('express');var router = express.Router();router.get('/', function(req, res){ res.end('index');});router.get('/123', function(){ res.end(123);});module.exports = router;
//routes/users.jsvar express = require('express');var router = express.Router();router.get('/', function(req, res) { res.end('users');});module.exports = router;

The Router created through express. router () is like a mini version of the app.

What the app can do, and what the router can do

We only encapsulate the logic in each routing module.

Result of the above Code:

Body-parser Middleware

As an entry-level article

Finally, let's talk about a middleware body-parser.

In fact, express has a lot of built-in middleware in version 3.x.

However, in version 4.x, all the middleware except static is removed.

So we need to install it separately.

The table is as follows:

Alibaba Cloud Express 3.0 Alibaba Cloud Express 4.0
BodyParser Body-parser
Compress Compression
CookieSession Cookie-session
Logger Morgan
CookieParser Cookie-parser
Session Express-session
Favicon Static-favicon
Response-time Response-time
Error-handler Errorhandler
Method-override Method-override
Timeout Connect-timeout
Vhost Vhost
Csrf Csurf

The post request is different just now.

The difference is that we need the body-parser middleware to process data.

Obtain data through req. body

Do not forget to download before use

npm install body-parser --save
// App. jsvar express = require ('express '); var bodyParser = require ('body-parser'); var path = require ('path'); var app = express (); app. use (bodyParser. json (); app. use (bodyParser. urlencoded ({extended: false}); app. get ('/', function (req, res) {res. send ('<form method = "POST" action = ". /form ">\< input type =" text "name =" user ">\< input type =" submit ">\</form> ') ;}); app. post ('/Form', function (req, res) {console. log (req. body); var user = req. body. user; res. send ('account: '+ user) ;}); app. listen (0, 3000 );

The following four methods are used to take different processing methods for the body content.

  1. BodyParser. json (options) process JSON data
  2. BodyParser. raw (options) processes buffer data
  3. BodyParser. text (options) process text data
  4. BodyParser. urlencoded (options) process UTF-8 encoded data

In this way, I first get the home page through the get request.

Submit a form to send a post request to the server

Server Response Results

Express-generator

Use the express-generator Application generator

You can quickly generate a project prototype for us.

Download express-generator from the directory of the project you want to generate

npm install express-generator

Enter

Express <project file name>

In this way, express will quickly generate necessary folders and codes.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.