Leilin Peng sharing framework Node.js Express

  Express Profile

  Express is a simple and flexible node.js Web application framework that provides a range of powerful features to help you create a variety of Web applications, and rich HTTP tools.

  Express can use to quickly build a fully functional website.

  Express framework core features:

  Middleware may be provided in response to the HTTP request.

  It defines the routing tables for performing an operation different HTTP request.

  You can dynamically render HTML pages by passing parameters to the template.

  Installation Express

  Express installation and save it to rely on the list:

  $ cnpm install express --save

  The above command will install the Express framework node_modules the current directory, the directory will be created automatically express node_modules directory. Several important module is the need to express frame mounted with:

  body-parser - node.js middleware, JSON, Raw, Text and URL-encoded data for processing.

  cookie-parser - This is a tool for parsing Cookie. May be taken by req.cookies to pass over the cookie, and to turn them into objects.

  multer - node.js middleware for processing enctype = "multipart / form-data" (set form MIME encoding) data form.

  $ cnpm install body-parser --save

  $ cnpm install cookie-parser --save

  $ cnpm install multer --save

  After installation, we can check the version number express use:

  $ cnpm list express

  /data/www/node

  └── [email protected] -> /Users/tianqixin/www/node/node_modules/.4.15.2@express

  The first example of a frame Express

  Next, we use the Express framework to output "Hello World".

  After the introduction of the following examples we express module, the client sends a request and, in response to "Hello World" string.

  Creating express_demo.js file, the code is as follows:

  express_demo.js file code:

  //express_demo.js file var express = require ( 'express'); var app = express (); app.get ( '/', function (req, res) {res.send ( 'Hello World');}) . var server = app.listen (8081, function () {var host = server.address () address var port = server.address () port console.log ( "application example, the access address of http:. //% s :% s ", host, port)})

  Execute the code above:

  $ node express_demo.js

  Application examples, access address http://0.0.0.0:8081

  Http://127.0.0.1:8081 browser access, the results shown below:

  Request and response

  Express application callback function parameters: request and response objects to process data requests and responses.

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

  // --

  })

  Introduce specific request and response objects:

  Request object - request object represents an HTTP request, the request comprising a query string parameter, contents, HTTP header attributes. Common attributes are:

  req.app: callback when an external file, accessible by express instance req.app

  req.baseUrl: get URL routing currently installed

  req.body / req.cookies: get 'request body "/ Cookies

  req.fresh / req.stale: to determine whether the request is still "fresh"

  req.hostname / req.ip: Get names and IP addresses

  req.originalUrl: get the original request URL

  req.params: obtaining routing parameters

  req.path: Get request path

  req.protocol: Gets the protocol type

  req.query: get the URL query string parameters

  req.route: Get the current matching route

  req.subdomains: get subdomain

  req.accepts (): checking the type of document requests acceptable

  req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: Returns the specified character set of a character encoding acceptable

  req.get (): Get the specified HTTP request header

  req.is (): if the request Content-Type header MIME type

  Response object - response object represents the HTTP response, HTTP that is sent to the client upon receiving the request response data. Common attributes are:

  res.app: Like req.app

  res.append (): Specifies additional HTTP header

  res.set () before resetting the head after res.append () provided

  res.cookie(name,value [,option]):设置Cookie

  opition: domain / expires / httpOnly / maxAge / path / secure / signed

  res.clearCookie():清除Cookie

  res.download (): file transfer path specified

  res.get (): returns the specified HTTP header

  res.json (): transfer in response JSON

  res.jsonp (): transfer JSONP response

  res.location (): Set Location HTTP response header only, is not provided or close response status code

  res.redirect (): Set Location HTTP response header, and sets the status code 302

  res.render (view, [locals], callback): rendering a view, while the rendered string is transmitted to the callback, if an error occurs next (err) during the rendering process will be automatically invoked. callback will be passed in a possible error occurred and after rendering the page, so it will not automatically output.

  res.send (): sends an HTTP response

  res.sendFile (path [, options] [, fn]): Specifies the transmission path file - are automatically set based on the file extension Content-Type

  res.set (): Set HTTP header, passing object may be provided a plurality of heads

  res.status (): Set HTTP status code

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

  routing

  We already know the basic application HTTP requests, and routing determines who (designated script) to respond to client requests.

  In the HTTP request, we can extract the URL and GET / POST requests by routing parameters.

  Next we extend Hello World, to add some features to handle more types of HTTP requests.

  Creating express_demo2.js file, the code is as follows:

  express_demo2.js file code:

  var express = require ( 'express'); var app = express (); // page output "Hello World" app.get ( '/', function (req, res) {console.log ( "Home GET request") ; res.send ( 'Hello GET');}) // POST request app.post ( '/', function (req, res) {console.log ( "Home POST request"); res.send ( 'Hello POST ');}) // / del_user page response app.get (' / del_user ', function (req, res) {console.log ( "/ del_user dELETE request response"); res.send (' delete page '); }) // / list_user page GET request app.get ( '/ list_user', function (req, res) {console.log ( "/ list_user GET request"); res.send ( 'user list page');}) // page of abcd, abxcd, ab123cd, etc. in response to the GET request app.get ( '/ ab * cd', function (req, res) {console.log ( "/ ab * cd GET request"); res.send ( 'regular match');}) var server = app.listen (8081, function () {var host = server.. Address () address var port = server.address () port console.log ( "application example, the access address of http: //% s:% s", host, port).})

  Execute the code above:

  $ node express_demo2.js

  Application examples, access address http://0.0.0.0:8081

  Then you can try different access http://127.0.0.1:8081 address, to see the effect.

  Http://127.0.0.1:8081/list_user browser access, the results shown below:

  Http://127.0.0.1:8081/abcd browser access, the results shown below:

  Http://127.0.0.1:8081/abcdefg browser access, the results shown below:

  Static files

  Express provides built-in middleware express.static to set a static file, such as: images, CSS, JavaScript and so on.

  You can use express.static middleware to set a static file path. For example, if you picture, CSS, JavaScript files in the public directory, you can write:

  app.use(express.static('public'));

  We can go to the public / images directory delegated some pictures, as follows:

  node_modules

  server.js

  public/

  public/images

  public/images/logo.png

  Let us modify the next "Hello World" application processing functionality to add static files.

  Creating express_demo3.js file, the code is as follows:

  express_demo3.js file code:

  var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/', function (req, res) { res.send('Hello World'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })

  执行以上代码:

  $ node express_demo3.js

  应用实例,访问地址为 http://0.0.0.0:8081

  执行以上代码:

  在浏览器中访问 http://127.0.0.1:8081/images/logo.png(本实例采用了码农教程的logo),结果如下图所示:

  GET 方法

  以下实例演示了在表单中通过 GET 方法提交两个参数,我们可以使用 server.js 文件内的 process_get 路由器来处理输入:

  index.htm 文件代码:

  

First Name:
Last Name:

 

  server.js 文件代码:

  var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.get('/process_get', function (req, res) { // 输出 JSON 格式 var response = { "first_name":req.query.first_name, "last_name":req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })

  执行以上代码:

  node server.js

  应用实例,访问地址为 http://0.0.0.0:8081

  浏览器访问 http://127.0.0.1:8081/index.htm,如图所示:

  现在你可以向表单输入数据,并提交,如下演示:

  POST 方法

  以下实例演示了在表单中通过 POST 方法提交两个参数,我们可以使用 server.js 文件内的 process_post 路由器来处理输入:

  index.htm 文件代码:

  

First Name:
Last Name:

 

  server.js 文件代码:

  var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // 创建 application/x-www-form-urlencoded 编码解析 var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/process_post', urlencodedParser, function (req, res) { // 输出 JSON 格式 var response = { "first_name":req.body.first_name, "last_name":req.body.last_name }; console.log(response); res.end(JSON.stringify(response)); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })

  执行以上代码:

  $ node server.js

  应用实例,访问地址为 http://0.0.0.0:8081

  浏览器访问 http://127.0.0.1:8081/index.htm,如图所示:

  现在你可以向表单输入数据,并提交,如下演示:

  文件上传

  以下我们创建一个用于上传文件的表单,使用 POST 方法,表单 enctype 属性设置为 multipart/form-data。

  index.htm 文件代码:

  

文件上传:

选择一个文件上传:


 

  server.js 文件代码:

  var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/file_upload', function (req, res) { console.log(req.files[0]); // 上传的文件信息 var des_file = __dirname + "/" + req.files[0].originalname; fs.readFile( req.files[0].path, function (err, data) { fs.writeFile(des_file, data, function (err) { if( err ){ console.log( err ); }else{ response = { message:'File uploaded successfully', filename:req.files[0].originalname }; } console.log( response ); res.end( JSON.stringify( response ) ); }); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })

  执行以上代码:

  $ node server.js

  应用实例,访问地址为 http://0.0.0.0:8081

  浏览器访问 http://127.0.0.1:8081/index.htm,如图所示:

  现在你可以向表单输入数据,并提交,如下演示:

  Cookie 管理

  我们可以使用中间件向 Node.js 服务器发送 cookie 信息,以下代码输出了客户端发送的 cookie 信息:

  express_cookie.js 文件代码:

  // express_cookie.js 文件 var express = require('express') var cookieParser = require('cookie-parser') var util = require('util'); var app = express() app.use(cookieParser()) app.get('/', function(req, res) { console.log("Cookies: " + util.inspect(req.cookies)); }) app.listen(8081)

  执行以上代码:

  $ node express_cookie.js

  现在你可以访问 http://127.0.0.1:8081 并查看终端信息的输出,如下演示:

(编辑:雷林鹏 来源:网络 侵删) 

Guess you like

Origin www.cnblogs.com/pengpeng1208/p/11458627.html