1. 程式人生 > 實用技巧 >Node.js Express框架

Node.js Express框架

Node.js Express框架

參考https://www.runoob.com/nodejs/nodejs-express-framework.html
Express核心特性

  • 可以設定中介軟體來響應HTTP請求
  • 定義了路由表用於執行不同的HTTP請求動作
  • 可以通過模板傳遞引數來動態渲染HTML頁面

第一個Express框架例項

使用Express框架輸出“Hello World”

var express = require('express')
var app = express();
    
    // GET請求
app.get('/', (req, res)=>{
	res.send('Hello World');
});

var server = app.listen(8081, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	console.log(host);
	console.log("應用例項,訪問地址為:http://%s:%s", host, port);
});

開啟瀏覽器輸入

  127.0.0.1:8081

結果:

請求和響應

Express應用使用回撥函式的引數:requestresponse物件來處理請求和響應的資料。

  // GET請求
  app.get(routerpath, function(request, response){});

routerpath可以是字串或正則表示式。

路由

路由決定了由誰(指定指令碼)去響應客戶端請求。
app.get(routerpath, function(request, response){});:GET請求的響應,routerpath可以是正則或字串
app.post(routerpath, function(request, response){});

:POST請求的響應,routerpath可以是正則或字串。

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

// GET請求
app.get('/', (req, res)=>{
	console.log("主頁GET請求");
	res.send('Hello GET');
});

// POST請求
app.post('/', (req, res)=>{
	console.log('主頁POST請求');
	res.send('Hello POST');
});

// /list_user頁面GET請求
app.get('/list_user', (req, res)=>{
	console.log("/list_user GET請求");
	res.send('使用者列表介面');
});

// /del_user頁面GET請求
app.get('/del_user', (req, res)=>{
	console.log("/del_user GET請求");
	res.send('刪除頁面');
});
// 對頁面abcd,abxcd,ab123cd等GET請求
app.get('/ab*cd', (req, res)=>{
	console.log('/ab*cd GET請求');
	res.send("正則匹配");
});

var server = app.listen(8081, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	console.log("應用例項,訪問地址為:http://%s:%s", host, port);
});

在瀏覽器中輸入:

  127.0.0.1:8081
  // 或者
  127.0.0.1:8081/list_user
  // 或者
  127.0.0.1:8081/del_user
  // 或者
  127.0.0.1:8081/ab任意字元cd

可以得到物件的頁面響應。

靜態檔案

Express提供了內建的中介軟體express.static來設定靜態資源(圖片,CSS,JavaScript等)。
使用express.static中介軟體設定靜態檔案的路徑:

  app.use('routerpath', express.static('path'));

routerpath是虛擬路徑,path為真實路徑,通過routerpath來訪問path中的資源。

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

app.use('/resources', express.static('public'));
// GET請求
app.get('/', (req, res)=>{
	console.log("主頁GET請求");
	res.send('Hello GET');
});

var server = app.listen(8081, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	console.log("應用例項,訪問地址為:http://%s:%s", host, port);
});

我的目錄結構:

結果:

GET方法

通過GET方法提交兩個引數,使用“/process_get”路由來處理輸入:
index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<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" /><br />
			<input type="submit" value="Submit"/>
		</form>
	</body>
</html>

main.js

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

app.use('/resources', express.static('public'));
// GET請求
app.get('/index.html', (req, res)=>{
	res.sendFile(__dirname+'/'+'index.html');
});

app.get('/process_get', (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, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	console.log("應用例項,訪問地址為:http://%s:%s", host, port);
});

瀏覽器中訪問

  127.0.0.1:8081/index.html

填寫並提交表單後,會跳轉到

  127.0.0.1:8081/process_get?firt_name=xxx&last_name=xxx

觀察到

和控制檯的輸出

  { first_name: 'admin', last_name: '123456' }

POST方法

index.html: 和GET方法類似,改為

,其他不變;
main.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('/resources', express.static('public'));
// GET請求
app.get('/index.html', (req, res)=>{
	res.sendFile(__dirname+'/'+'index.html');
});

app.post('/process_post', urlencodedParser, (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, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	console.log("應用例項,訪問地址為:http://%s:%s", host, port);
});

結果:
瀏覽器端:

控制檯:

  { first_name: 'admin', last_name: '123456' }

檔案上傳

使用POST方法和一個form表單,同時將表單的enctype屬性設定為multipart/form-data。
index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<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="Submit"/>
		</form>
	</body>
</html>

main.js

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

var bodyParser = require('body-parser');
var multer = require('multer');

app.use('/public', express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: '/tmp/'}).array('image'));

app.get('/index.html', (req, res)=>{
	res.sendFile(__dirname+'/'+"index.html");
});

app.post('/file_upload', (req, res)=>{
	var file = req.files[0];//上傳的第一個檔案
	console.log(file);//上傳的檔案資訊
	
	var des_file = __dirname+'/'+file.originalname;
	fs.readFile(file.path, (err, data)=>{
		fs.writeFile(des_file, data, (err)=>{
			var response = {message:'',filename:file.originalname};
			if(err){
				console.log(err);
				response.message = 'File upload failed';
			}
			else{
				response.message = 'File uploaded successfully';
			}
			console.log(response);
			res.end(JSON.stringify(response));
		});
	});
});

var server = app.listen(8081, ()=>{
	var host = server.address().address;
	var port = server.address().port;
	
	console.log("應用例項,訪問地址:http://%s%s", host, port);
});

結果:

選擇檔案後:

點選上傳後:

控制檯輸出:

  {
    fieldname: 'image',
    originalname: 'smile.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    destination: '/tmp/',
    filename: 'aec0dc0dbfbdaedc56325e246a61cbe3',
    path: '\\tmp\\aec0dc0dbfbdaedc56325e246a61cbe3',
    size: 12281
  }
  { message: 'File uploaded successfully', filename: 'smile.jpg' }

並發現當前目錄多了一個剛剛上傳的檔案-smile.jpg。

Cookie管理

使用中介軟體向Node.js伺服器傳送cookie資訊:

var express = require('express');
var cookieParser = require('cookie-parser');
var util = require('util');

var app = express();
app.use(cookieParser());

app.get('/', (req, res)=>{
	console.log("Cookies: "+util.inspect(req.cookies));
	res.send("Cookies: "+util.inspect(req.cookies));
});

app.listen(8081);

結果:
瀏覽器輸入

  127.0.0.1:8081

觀察瀏覽器和控制檯的輸出。