Node.js學習筆記5——Express

Express provide a higher level interface of http module.

Install express:

$ npm install express --save

these important modules will be installed with express.

  • body-parser: middleware of Node.js, to handle JSON, Raw, Text and URL encoding data.
  • cookie-parser: tool to parse cookie. we can get cookie by req.cookies, and parse into object
  • multer: middleware of Node.js. to handle form data like enctype="multipart/form-data"
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Example

//express_demo.js
var express = require('express');
var app = express();
 
app.get('/', function (req, res) {
   res.send('Hello World');
})
 
var server = app.listen(80, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

Request and Response

Request:

  1. req.app:當callback為外部文件時,用req.app訪問express的實例
  2. req.baseUrl:獲取路由當前安裝的URL路徑
  3. req.body / req.cookies:獲得「請求主體」/ Cookies
  4. req.fresh / req.stale:判斷請求是否還「新鮮」
  5. req.hostname / req.ip:獲取主機名和IP地址
  6. req.originalUrl:獲取原始請求URL
  7. req.params:獲取路由的parameters
  8. req.path:獲取請求路徑
  9. req.protocol:獲取協(xié)議類型
  10. req.query:獲取URL的查詢參數(shù)串
  11. req.route:獲取當前匹配的路由
  12. req.subdomains:獲取子域名
  13. req.accepts():檢查可接受的請求的文檔類型
  14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages:返回指定字符集的第一個可接受字符編碼
  15. req.get():獲取指定的HTTP請求頭
  16. req.is():判斷請求頭Content-Type的MIME類型

Response:

  1. res.app:同req.app一樣
  2. res.append():追加指定HTTP頭
  3. res.set(): 在res.append()后將重置之前設(shè)置的頭
  4. res.cookie(name,value [,option]):設(shè)置Cookie
  5. opition: domain / expires / httpOnly / maxAge / path / secure / signed
  6. res.clearCookie():清除Cookie
  7. res.download():傳送指定路徑的文件
  8. res.get():返回指定的HTTP頭
  9. res.json():傳送JSON響應(yīng)
  10. res.jsonp():傳送JSONP響應(yīng)
  11. res.location():只設(shè)置響應(yīng)的Location HTTP頭,不設(shè)置狀態(tài)碼或者close response
  12. res.redirect():設(shè)置響應(yīng)的Location HTTP頭,并且設(shè)置狀態(tài)碼302
  13. res.send():傳送HTTP響應(yīng)
  14. res.sendFile(path [,options] [,fn]):傳送指定路徑的文件 -會自動根據(jù)文件extension設(shè)定Content-Type
  15. res.set():設(shè)置HTTP頭,傳入object可以一次設(shè)置多個頭
  16. res.status():設(shè)置HTTP狀態(tài)碼
  17. res.type():設(shè)置Content-Type的MIME類型

Route

var express = require('express');
var app = express();
 
//  主頁輸出 "Hello World"
app.get('/', function (req, res) {
   console.log("主頁 GET 請求");
   res.send('Hello GET');
})
 
 
//  POST 請求
app.post('/', function (req, res) {
   console.log("主頁 POST 請求");
   res.send('Hello POST');
})
 
//  /del_user 頁面響應(yīng)
app.get('/del_user', function (req, res) {
   console.log("/del_user 響應(yīng) DELETE 請求");
   res.send('刪除頁面');
})
 
//  /list_user 頁面 GET 請求
app.get('/list_user', function (req, res) {
   console.log("/list_user GET 請求");
   res.send('用戶列表頁面');
})
 
// 對頁面 abcd, abxcd, ab123cd, 等響應(yīng) GET 請求
app.get('/ab*cd', function(req, res) {   
   console.log("/ab*cd GET 請求");
   res.send('正則匹配');
})
 
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

Static Files

We can export static files using express.static

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

and put some pics in public dir:

node_modules
server.js
public/
public/images
public/images/logo.png

Demo:

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("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

now, we can visit pic using url: http://127.0.0.1:8081/images/logo.png

Get Method

index.html:

<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name">  <br>
 
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

server.js:

var express = require('express');
var app = express();
 
app.use(express.static('public'));
 
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
 
app.get('/process_get', function (req, res) {
 
   // 輸出 JSON 格式
   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("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

POST Method

index.html:

<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name">  <br>
 
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
 
// 創(chuàng)建 application/x-www-form-urlencoded 編碼解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
app.use(express.static('public'));
 
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
 
app.post('/process_post', urlencodedParser, function (req, res) {
 
   // 輸出 JSON 格式
   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("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

File Upload

index.html

<html>
<head>
<title>文件上傳表單</title>
</head>
<body>
<h3>文件上傳:</h3>
選擇一個文件上傳: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上傳文件" />
</form>
</body>
</html>

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("應(yīng)用實例,訪問地址為 http://%s:%s", host, port)
 
})

Cookie management

server.js

var express      = require('express')
var cookieParser = require('cookie-parser')
 
var app = express()
app.use(cookieParser())
 
app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})
 
app.listen(8081)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容