W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Express是目前最流行的基于Node.js的Web開(kāi)發(fā)框架,提供各種模塊,可以快速地搭建一個(gè)具有完整功能的網(wǎng)站。
Express的上手非常簡(jiǎn)單,首先新建一個(gè)項(xiàng)目目錄,假定叫做hello-world。
$ mkdir hello-world
進(jìn)入該目錄,新建一個(gè)package.json文件,內(nèi)容如下。
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "4.x"
}
}
上面代碼定義了項(xiàng)目的名稱、描述、版本等,并且指定需要4.0版本以上的Express。
然后,就可以安裝了。
$ npm install
安裝了Express及其依賴的模塊以后,在項(xiàng)目根目錄下,新建一個(gè)啟動(dòng)文件,假定叫做index.js。
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
上面代碼運(yùn)行之后,訪問(wèn)http://localhost:8080
,就會(huì)在瀏覽器中打開(kāi)當(dāng)前目錄的public子目錄。如果public目錄之中有一個(gè)圖片文件my_image.png,那么可以用http://localhost:8080/my_image.png
訪問(wèn)該文件。
你也可以在index.js之中,生成動(dòng)態(tài)網(wǎng)頁(yè)。
// index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.listen(3000);
然后,在命令行下運(yùn)行下面的命令,就可以在瀏覽器中訪問(wèn)項(xiàng)目網(wǎng)站了。
$ node index
默認(rèn)情況下,網(wǎng)站運(yùn)行在本機(jī)的3000端口,網(wǎng)頁(yè)顯示Hello World。
index.js中的app.get
用于指定不同的訪問(wèn)路徑所對(duì)應(yīng)的回調(diào)函數(shù),這叫做“路由”(routing)。上面代碼只指定了根目錄的回調(diào)函數(shù),因此只有一個(gè)路由記錄。實(shí)際應(yīng)用中,可能有多個(gè)路由記錄。
// index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.get('/customer', function(req, res){
res.send('customer page');
});
app.get('/admin', function(req, res){
res.send('admin page');
});
app.listen(3000);
這時(shí),最好就把路由放到一個(gè)單獨(dú)的文件中,比如新建一個(gè)routes子目錄。
// routes/index.js
module.exports = function (app) {
app.get('/', function (req, res) {
res.send('Hello world');
});
app.get('/customer', function(req, res){
res.send('customer page');
});
app.get('/admin', function(req, res){
res.send('admin page');
});
};
然后,原來(lái)的index.js就變成下面這樣。
// index.js
var express = require('express');
var app = express();
var routes = require('./routes')(app);
app.listen(3000);
使用Express搭建HTTPs加密服務(wù)器,也很簡(jiǎn)單。
var fs = require('fs');
var options = {
key: fs.readFileSync('E:/ssl/myserver.key'),
cert: fs.readFileSync('E:/ssl/myserver.crt'),
passphrase: '1234'
};
var https = require('https');
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello World Expressjs');
});
var server = https.createServer(options, app);
server.listen(8084);
console.log('Server is running on port 8084');
Express框架建立在node.js內(nèi)置的http模塊上。 http模塊生成服務(wù)器的原始代碼如下。
var http = require("http");
var app = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello world!");
});
app.listen(3000, "localhost");
上面代碼的關(guān)鍵是http模塊的createServer方法,表示生成一個(gè)HTTP服務(wù)器實(shí)例。該方法接受一個(gè)回調(diào)函數(shù),該回調(diào)函數(shù)的參數(shù),分別為代表HTTP請(qǐng)求和HTTP回應(yīng)的request對(duì)象和response對(duì)象。
Express框架的核心是對(duì)http模塊的再包裝。上面的代碼用Express改寫(xiě)如下。
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.listen(3000);
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
http.createServer(app).listen(1337);
比較兩段代碼,可以看到它們非常接近,唯一的差別是createServer方法的參數(shù),從一個(gè)回調(diào)函數(shù)變成了一個(gè)Epress對(duì)象的實(shí)例。而這個(gè)實(shí)例使用了use方法,加載了與上一段代碼相同的回調(diào)函數(shù)。
Express框架等于在http模塊之上,加了一個(gè)中間層,而use方法則相當(dāng)于調(diào)用中間件。
簡(jiǎn)單說(shuō),中間件(middleware)就是處理HTTP請(qǐng)求的函數(shù),用來(lái)完成各種特定的任務(wù),比如檢查用戶是否登錄、分析數(shù)據(jù)、以及其他在需要最終將數(shù)據(jù)發(fā)送給用戶之前完成的任務(wù)。它最大的特點(diǎn)就是,一個(gè)中間件處理完,再傳遞給下一個(gè)中間件。
node.js的內(nèi)置模塊http的createServer方法,可以生成一個(gè)服務(wù)器實(shí)例,該實(shí)例允許在運(yùn)行過(guò)程中,調(diào)用一系列函數(shù)(也就是中間件)。當(dāng)一個(gè)HTTP請(qǐng)求進(jìn)入服務(wù)器,服務(wù)器實(shí)例會(huì)調(diào)用第一個(gè)中間件,完成后根據(jù)設(shè)置,決定是否再調(diào)用下一個(gè)中間件。中間件內(nèi)部可以使用服務(wù)器實(shí)例的response對(duì)象(ServerResponse,即回調(diào)函數(shù)的第二個(gè)參數(shù)),以及一個(gè)next回調(diào)函數(shù)(即第三個(gè)參數(shù))。每個(gè)中間件都可以對(duì)HTTP請(qǐng)求(request對(duì)象)做出回應(yīng),并且決定是否調(diào)用next方法,將request對(duì)象再傳給下一個(gè)中間件。
一個(gè)不進(jìn)行任何操作、只傳遞request對(duì)象的中間件,大概是下面這樣:
function uselessMiddleware(req, res, next) {
next();
}
上面代碼的next為中間件的回調(diào)函數(shù)。如果它帶有參數(shù),則代表拋出一個(gè)錯(cuò)誤,參數(shù)為錯(cuò)誤文本。
function uselessMiddleware(req, res, next) {
next('出錯(cuò)了!');
}
拋出錯(cuò)誤以后,后面的中間件將不再執(zhí)行,直到發(fā)現(xiàn)一個(gè)錯(cuò)誤處理函數(shù)為止。
use是express調(diào)用中間件的方法,它返回一個(gè)函數(shù)。下面是一個(gè)連續(xù)調(diào)用兩個(gè)中間件的例子。
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
console.log("In comes a " + request.method + " to " + request.url);
next();
});
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
http.createServer(app).listen(1337);
上面代碼先調(diào)用第一個(gè)中間件,在控制臺(tái)輸出一行信息,然后通過(guò)next方法,調(diào)用第二個(gè)中間件,輸出HTTP回應(yīng)。由于第二個(gè)中間件沒(méi)有調(diào)用next方法,所以不再request對(duì)象就不再向后傳遞了。
使用use方法,可以根據(jù)請(qǐng)求的網(wǎng)址,返回不同的網(wǎng)頁(yè)內(nèi)容。
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
if (request.url == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
} else {
next();
}
});
app.use(function(request, response, next) {
if (request.url == "/about") {
response.writeHead(200, { "Content-Type": "text/plain" });
} else {
next();
}
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
上面代碼通過(guò)request.url屬性,判斷請(qǐng)求的網(wǎng)址,從而返回不同的內(nèi)容。
除了在回調(diào)函數(shù)內(nèi)部,判斷請(qǐng)求的網(wǎng)址,Express也允許將請(qǐng)求的網(wǎng)址寫(xiě)在use方法的第一個(gè)參數(shù)。
app.use('/', someMiddleware);
上面代碼表示,只對(duì)根目錄的請(qǐng)求,調(diào)用某個(gè)中間件。
因此,上面的代碼可以寫(xiě)成下面的樣子。
var express = require("express");
var http = require("http");
var app = express();
app.use("/", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
});
app.use("/about", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
針對(duì)不同的請(qǐng)求,Express提供了use方法的一些別名。比如,上面代碼也可以用別名的形式來(lái)寫(xiě)。
var express = require("express");
var http = require("http");
var app = express();
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});
app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
});
app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
});
app.get("*", function(request, response) {
response.end("404!");
});
http.createServer(app).listen(1337);
上面代碼的all方法表示,所有請(qǐng)求都必須通過(guò)該中間件,參數(shù)中的“*”表示對(duì)所有路徑有效。get方法則是只有GET動(dòng)詞的HTTP請(qǐng)求通過(guò)該中間件,它的第一個(gè)參數(shù)是請(qǐng)求的路徑。由于get方法的回調(diào)函數(shù)沒(méi)有調(diào)用next方法,所以只要有一個(gè)中間件被調(diào)用了,后面的中間件就不會(huì)再被調(diào)用了。
除了get方法以外,Express還提供post、put、delete方法,即HTTP動(dòng)詞都是Express的方法。
這些方法的第一個(gè)參數(shù),都是請(qǐng)求的路徑。除了絕對(duì)匹配以外,Express允許模式匹配。
app.get("/hello/:who", function(req, res) {
res.end("Hello, " + req.params.who + ".");
});
上面代碼將匹配“/hello/alice”網(wǎng)址,網(wǎng)址中的alice將被捕獲,作為req.params.who屬性的值。需要注意的是,捕獲后需要對(duì)網(wǎng)址進(jìn)行檢查,過(guò)濾不安全字符,上面的寫(xiě)法只是為了演示,生產(chǎn)中不應(yīng)這樣直接使用用戶提供的值。
如果在模式參數(shù)后面加上問(wèn)號(hào),表示該參數(shù)可選。
app.get('/hello/:who?',function(req,res) {
if(req.params.id) {
res.end("Hello, " + req.params.who + ".");
}
else {
res.send("Hello, Guest.");
}
});
下面是一些更復(fù)雜的模式匹配的例子。
app.get('/forum/:fid/thread/:tid', middleware)
// 匹配/commits/71dbb9c
// 或/commits/71dbb9c..4c084f9這樣的git格式的網(wǎng)址
app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
var from = req.params[0];
var to = req.params[1] || 'HEAD';
res.send('commit range ' + from + '..' + to);
});
set方法用于指定變量的值。
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
上面代碼使用set方法,為系統(tǒng)變量“views”和“view engine”指定值。
(1)response.redirect方法
response.redirect方法允許網(wǎng)址的重定向。
response.redirect("/hello/anime");
response.redirect("http://www.example.com");
response.redirect(301, "http://www.example.com");
(2)response.sendFile方法
response.sendFile方法用于發(fā)送文件。
response.sendFile("/path/to/anime.mp4");
(3)response.render方法
response.render方法用于渲染網(wǎng)頁(yè)模板。
app.get("/", function(request, response) {
response.render("index", { message: "Hello World" });
});
上面代碼使用render方法,將message變量傳入index模板,渲染成HTML網(wǎng)頁(yè)。
(1)request.ip
request.ip屬性用于獲得HTTP請(qǐng)求的IP地址。
(2)request.files
request.files用于獲取上傳的文件。
上一節(jié)使用express命令自動(dòng)建立項(xiàng)目,也可以不使用這個(gè)命令,手動(dòng)新建所有文件。
先建立一個(gè)項(xiàng)目目錄(假定這個(gè)目錄叫做demo)。進(jìn)入該目錄,新建一個(gè)package.json文件,寫(xiě)入項(xiàng)目的配置信息。
{
"name": "demo",
"description": "My First Express App",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
在項(xiàng)目目錄中,新建文件app.js。項(xiàng)目的代碼就放在這個(gè)文件里面。
var express = require('express');
var app = express();
上面代碼首先加載express模塊,賦給變量express。然后,生成express實(shí)例,賦給變量app。
接著,設(shè)定express實(shí)例的參數(shù)。
// 設(shè)定port變量,意為訪問(wèn)端口
app.set('port', process.env.PORT || 3000);
// 設(shè)定views變量,意為視圖存放的目錄
app.set('views', path.join(__dirname, 'views'));
// 設(shè)定view engine變量,意為網(wǎng)頁(yè)模板引擎
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
// 設(shè)定靜態(tài)文件目錄,比如本地文件
// 目錄為demo/public/images,訪問(wèn)
// 網(wǎng)址則顯示為http://localhost:3000/images
app.use(express.static(path.join(__dirname, 'public')));
上面代碼中的set方法用于設(shè)定內(nèi)部變量,use方法用于調(diào)用express的中間件。
最后,調(diào)用實(shí)例方法listen,讓其監(jiān)聽(tīng)事先設(shè)定的端口(3000)。
app.listen(app.get('port'));
這時(shí),運(yùn)行下面的命令,就可以在瀏覽器訪問(wèn)http://127.0.0.1:3000。
node app.js
網(wǎng)頁(yè)提示“Cannot GET /”,表示沒(méi)有為網(wǎng)站的根路徑指定可以顯示的內(nèi)容。所以,下一步就是配置路由。
所謂“路由”,就是指為不同的訪問(wèn)路徑,指定不同的處理方法。
(1)指定根路徑
在app.js之中,先指定根路徑的處理方法。
app.get('/', function(req, res) {
res.send('Hello World');
});
上面代碼的get方法,表示處理客戶端發(fā)出的GET請(qǐng)求。相應(yīng)的,還有app.post、app.put、app.del(delete是JavaScript保留字,所以改叫del)方法。
get方法的第一個(gè)參數(shù)是訪問(wèn)路徑,正斜杠(/)就代表根路徑;第二個(gè)參數(shù)是回調(diào)函數(shù),它的req參數(shù)表示客戶端發(fā)來(lái)的HTTP請(qǐng)求,res參數(shù)代表發(fā)向客戶端的HTTP回應(yīng),這兩個(gè)參數(shù)都是對(duì)象。在回調(diào)函數(shù)內(nèi)部,使用HTTP回應(yīng)的send方法,表示向?yàn)g覽器發(fā)送一個(gè)字符串。然后,運(yùn)行下面的命令。
node app.js
此時(shí),在瀏覽器中訪問(wèn)http://127.0.0.1:3000,網(wǎng)頁(yè)就會(huì)顯示“Hello World”。
如果需要指定HTTP頭信息,回調(diào)函數(shù)就必須換一種寫(xiě)法,要使用setHeader方法與end方法。
app.get('/', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
(2)指定特定路徑
上面是處理根目錄的情況,下面再舉一個(gè)例子。假定用戶訪問(wèn)/api路徑,希望返回一個(gè)JSON字符串。這時(shí),get可以這樣寫(xiě)。
app.get('/api', function(request, response) {
response.send({name:"張三",age:40});
});
上面代碼表示,除了發(fā)送字符串,send方法還可以直接發(fā)送對(duì)象。重新啟動(dòng)node以后,再訪問(wèn)路徑/api,瀏覽器就會(huì)顯示一個(gè)JSON對(duì)象。
{
"name": "張三",
"age": 40
}
我們也可以把a(bǔ)pp.get的回調(diào)函數(shù),封裝成模塊。先在routes目錄下面建立一個(gè)api.js文件。
// routes/api.js
exports.index = function (req, res){
res.json(200, {name:"張三",age:40});
}
然后,在app.js中加載這個(gè)模塊。
// app.js
var api = require('./routes/api');
app.get('/api', api.index);
現(xiàn)在訪問(wèn)時(shí),就會(huì)顯示與上一次同樣的結(jié)果。
如果只向?yàn)g覽器發(fā)送簡(jiǎn)單的文本信息,上面的方法已經(jīng)夠用;但是如果要向?yàn)g覽器發(fā)送復(fù)雜的內(nèi)容,還是應(yīng)該使用網(wǎng)頁(yè)模板。
在項(xiàng)目目錄之中,建立一個(gè)子目錄views,用于存放網(wǎng)頁(yè)模板。
假定這個(gè)項(xiàng)目有三個(gè)路徑:根路徑(/)、自我介紹(/about)和文章(/article)。那么,app.js可以這樣寫(xiě):
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendfile('./views/index.html');
});
app.get('/about', function(req, res) {
res.sendfile('./views/about.html');
});
app.get('/article', function(req, res) {
res.sendfile('./views/article.html');
});
app.listen(3000);
上面代碼表示,三個(gè)路徑分別對(duì)應(yīng)views目錄中的三個(gè)模板:index.html、about.html和article.html。另外,向服務(wù)器發(fā)送信息的方法,從send變成了sendfile,后者專門(mén)用于發(fā)送文件。
假定index.html的內(nèi)容如下:
<html>
<head>
<title>首頁(yè)</title>
</head>
<body>
<h1>Express Demo</h1>
<footer>
<p>
<a href="/">首頁(yè)</a> - <a href="/about">自我介紹</a> - <a href="/article">文章</a>
</p>
</footer>
</body>
</html>
上面代碼是一個(gè)靜態(tài)網(wǎng)頁(yè)。如果想要展示動(dòng)態(tài)內(nèi)容,就必須使用動(dòng)態(tài)網(wǎng)頁(yè)模板。
網(wǎng)站真正的魅力在于動(dòng)態(tài)網(wǎng)頁(yè),下面我們來(lái)看看,如何制作一個(gè)動(dòng)態(tài)網(wǎng)頁(yè)的網(wǎng)站。
Express支持多種模板引擎,這里采用Handlebars模板引擎的服務(wù)器端版本hbs模板引擎。
先安裝hbs。
npm install hbs --save-dev
上面代碼將hbs模塊,安裝在項(xiàng)目目錄的子目錄node_modules之中。save-dev參數(shù)表示,將依賴關(guān)系寫(xiě)入package.json文件。安裝以后的package.json文件變成下面這樣:
// package.json文件
{
"name": "demo",
"description": "My First Express App",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
},
"devDependencies": {
"hbs": "~2.3.1"
}
}
安裝模板引擎之后,就要改寫(xiě)app.js。
// app.js文件
var express = require('express');
var app = express();
// 加載hbs模塊
var hbs = require('hbs');
// 指定模板文件的后綴名為html
app.set('view engine', 'html');
// 運(yùn)行hbs模塊
app.engine('html', hbs.__express);
app.get('/', function (req, res){
res.render('index');
});
app.get('/about', function(req, res) {
res.render('about');
});
app.get('/article', function(req, res) {
res.render('article');
});
上面代碼改用render方法,對(duì)網(wǎng)頁(yè)模板進(jìn)行渲染。render方法的參數(shù)就是模板的文件名,默認(rèn)放在子目錄views之中,后綴名已經(jīng)在前面指定為html,這里可以省略。所以,res.render('index') 就是指,把子目錄views下面的index.html文件,交給模板引擎hbs渲染。
渲染是指將數(shù)據(jù)代入模板的過(guò)程。實(shí)際運(yùn)用中,數(shù)據(jù)都是保存在數(shù)據(jù)庫(kù)之中的,這里為了簡(jiǎn)化問(wèn)題,假定數(shù)據(jù)保存在一個(gè)腳本文件中。
在項(xiàng)目目錄中,新建一個(gè)文件blog.js,用于存放數(shù)據(jù)。blog.js的寫(xiě)法符合CommonJS規(guī)范,使得它可以被require語(yǔ)句加載。
// blog.js文件
var entries = [
{"id":1, "title":"第一篇", "body":"正文", "published":"6/2/2013"},
{"id":2, "title":"第二篇", "body":"正文", "published":"6/3/2013"},
{"id":3, "title":"第三篇", "body":"正文", "published":"6/4/2013"},
{"id":4, "title":"第四篇", "body":"正文", "published":"6/5/2013"},
{"id":5, "title":"第五篇", "body":"正文", "published":"6/10/2013"},
{"id":6, "title":"第六篇", "body":"正文", "published":"6/12/2013"}
];
exports.getBlogEntries = function (){
return entries;
}
exports.getBlogEntry = function (id){
for(var i=0; i < entries.length; i++){
if(entries[i].id == id) return entries[i];
}
}
接著,新建模板文件index.html。
<!-- views/index.html文件 -->
<h1>文章列表</h1>
{{#each entries}}
<p>
<a href="/article/{{id}}">{{title}}</a><br/>
Published: {{published}}
</p>
{{/each}}
模板文件about.html。
<!-- views/about.html文件 -->
<h1>自我介紹</h1>
<p>正文</p>
模板文件article.html。
<!-- views/article.html文件 -->
<h1>{{blog.title}}</h1>
Published: {{blog.published}}
<p/>
{{blog.body}}
可以看到,上面三個(gè)模板文件都只有網(wǎng)頁(yè)主體。因?yàn)榫W(wǎng)頁(yè)布局是共享的,所以布局的部分可以單獨(dú)新建一個(gè)文件layout.html。
<!-- views/layout.html文件 -->
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{body}}}
<footer>
<p>
<a href="/">首頁(yè)</a> - <a href="/about">自我介紹</a>
</p>
</footer>
</body>
</html>
最后,改寫(xiě)app.js文件。
// app.js文件
var express = require('express');
var app = express();
var hbs = require('hbs');
// 加載數(shù)據(jù)模塊
var blogEngine = require('./blog');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.render('index',{title:"最近文章", entries:blogEngine.getBlogEntries()});
});
app.get('/about', function(req, res) {
res.render('about', {title:"自我介紹"});
});
app.get('/article/:id', function(req, res) {
var entry = blogEngine.getBlogEntry(req.params.id);
res.render('article',{title:entry.title, blog:entry});
});
app.listen(3000);
上面代碼中的render方法,現(xiàn)在加入了第二個(gè)參數(shù),表示模板變量綁定的數(shù)據(jù)。
現(xiàn)在重啟node服務(wù)器,然后訪問(wèn)http://127.0.0.1:3000。
node app.js
可以看得,模板已經(jīng)使用加載的數(shù)據(jù)渲染成功了。
模板文件默認(rèn)存放在views子目錄。這時(shí),如果要在網(wǎng)頁(yè)中加載靜態(tài)文件(比如樣式表、圖片等),就需要另外指定一個(gè)存放靜態(tài)文件的目錄。
app.use(express.static('public'));
上面代碼在文件app.js之中,指定靜態(tài)文件存放的目錄是public。于是,當(dāng)瀏覽器發(fā)出非HTML文件請(qǐng)求時(shí),服務(wù)器端就到public目錄尋找這個(gè)文件。比如,瀏覽器發(fā)出如下的樣式表請(qǐng)求:
<link href="/bootstrap/css/bootstrap.css" rel="stylesheet">
服務(wù)器端就到public/bootstrap/css/目錄中尋找bootstrap.css文件。
Express 4.0的Router用法,做了大幅改變,增加了很多新的功能。Router成了一個(gè)單獨(dú)的組件,好像小型的express應(yīng)用程序一樣,有自己的use、get、param和route方法。
Express 4.0的router對(duì)象,需要單獨(dú)新建。然后,使用該對(duì)象的HTTP動(dòng)詞方法,為不同的訪問(wèn)路徑,指定回調(diào)函數(shù);最后,掛載到某個(gè)路徑
var router = express.Router();
router.get('/', function(req, res) {
res.send('首頁(yè)');
});
router.get('/about', function(req, res) {
res.send('關(guān)于');
});
app.use('/', router);
上面代碼先定義了兩個(gè)訪問(wèn)路徑,然后將它們掛載到根目錄。如果最后一行改為app.use('/app', router),則相當(dāng)于/app和/app/about這兩個(gè)路徑,指定了回調(diào)函數(shù)。
這種掛載路徑和router對(duì)象分離的做法,為程序帶來(lái)了更大的靈活性,既可以定義多個(gè)router對(duì)象,也可以為將同一個(gè)router對(duì)象掛載到多個(gè)路徑。
router實(shí)例對(duì)象的route方法,可以接受訪問(wèn)路徑作為參數(shù)。
var router = express.Router();
router.route('/api')
.post(function(req, res) {
// ...
})
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err) res.send(err);
res.json(bears);
});
});
app.use('/', router);
use方法為router對(duì)象指定中間件,即在數(shù)據(jù)正式發(fā)給用戶之前,對(duì)數(shù)據(jù)進(jìn)行處理。下面就是一個(gè)中間件的例子。
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
上面代碼中,回調(diào)函數(shù)的next參數(shù),表示接受其他中間件的調(diào)用。函數(shù)體中的next(),表示將數(shù)據(jù)傳遞給下一個(gè)中間件。
注意,中間件的放置順序很重要,等同于執(zhí)行順序。而且,中間件必須放在HTTP動(dòng)詞方法之前,否則不會(huì)執(zhí)行。
router對(duì)象的param方法用于路徑參數(shù)的處理,可以
router.param('name', function(req, res, next, name) {
// 對(duì)name進(jìn)行驗(yàn)證或其他處理……
console.log(name);
req.name = name;
next();
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.name + '!');
});
上面代碼中,get方法為訪問(wèn)路徑指定了name參數(shù),param方法則是對(duì)name參數(shù)進(jìn)行處理。注意,param方法必須放在HTTP動(dòng)詞方法之前。
假定app是Express的實(shí)例對(duì)象,Express 4.0為該對(duì)象提供了一個(gè)route屬性。app.route實(shí)際上是express.Router()的縮寫(xiě)形式,除了直接掛載到根路徑。因此,對(duì)同一個(gè)路徑指定get和post方法的回調(diào)函數(shù),可以寫(xiě)成鏈?zhǔn)叫问健?/p>
app.route('/login')
.get(function(req, res) {
res.send('this is the login form');
})
.post(function(req, res) {
console.log('processing');
res.send('processing the login form!');
});
上面代碼的這種寫(xiě)法,顯然非常簡(jiǎn)潔清晰。
首先,在網(wǎng)頁(yè)插入上傳文件的表單。
<form action="/pictures/upload" method="POST" enctype="multipart/form-data">
Select an image to upload:
<input type="file" name="image">
<input type="submit" value="Upload Image">
</form>
然后,服務(wù)器腳本建立指向/upload
目錄的路由。這時(shí)可以安裝multer模塊,它提供了上傳文件的許多功能。
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
// 設(shè)定限制,每次最多上傳1個(gè)文件,文件大小不超過(guò)1MB
limits: {fileSize: 1000000, files:1},
})
router.post('/upload', uploading, function(req, res) {
})
module.exports = router
上面代碼是上傳文件到本地目錄。下面是上傳到Amazon S3的例子。
首先,在S3上面新增CORS配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
上面的配置允許任意電腦向你的bucket發(fā)送HTTP請(qǐng)求。
然后,安裝aws-sdk。
$ npm install aws-sdk --save
下面是服務(wù)器腳本。
var express = require('express');
var router = express.Router();
var aws = require('aws-sdk');
router.get('/', function(req, res) {
res.render('index')
})
var AWS_ACCESS_KEY = 'your_AWS_access_key'
var AWS_SECRET_KEY = 'your_AWS_secret_key'
var S3_BUCKET = 'images_upload'
router.get('/sign', function(req, res) {
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});
var s3 = new aws.S3()
var options = {
Bucket: S3_BUCKET,
Key: req.query.file_name,
Expires: 60,
ContentType: req.query.file_type,
ACL: 'public-read'
}
s3.getSignedUrl('putObject', options, function(err, data){
if(err) return res.send('Error with S3')
res.json({
signed_request: data,
url: 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + req.query.file_name
})
})
})
module.exports = router
上面代碼中,用戶訪問(wèn)/sign
路徑,正確登錄后,會(huì)收到一個(gè)JSON對(duì)象,里面是S3返回的數(shù)據(jù)和一個(gè)暫時(shí)用來(lái)接收上傳文件的URL,有效期只有60秒。
瀏覽器代碼如下。
// HTML代碼為
// <br>Please select an image
// <input type="file" id="image">
// <br>
// <img id="preview">
document.getElementById("image").onchange = function() {
var file = document.getElementById("image").files[0]
if (!file) return
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
document.getElementById("preview").src = response.url
})
})
}
function sign_request(file, done) {
var xhr = new XMLHttpRequest()
xhr.open("GET", "/sign?file_name=" + file.name + "&file_type=" + file.type)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
done(response)
}
}
xhr.send()
}
function upload(file, signed_request, url, done) {
var xhr = new XMLHttpRequest()
xhr.open("PUT", signed_request)
xhr.setRequestHeader('x-amz-acl', 'public-read')
xhr.onload = function() {
if (xhr.status === 200) {
done()
}
}
xhr.send(file)
}
上面代碼首先監(jiān)聽(tīng)file控件的change事件,一旦有變化,就先向服務(wù)器要求一個(gè)臨時(shí)的上傳URL,然后向該URL上傳文件。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: