[TOC]
## 概述
Express是目前最流行的基于Node.js的Web開發框架,提供各種模塊,可以快速地搭建一個具有完整功能的網站。
Express的上手非常簡單,首先新建一個項目目錄,假定叫做hello-world。
~~~
$ mkdir hello-world
~~~
進入該目錄,新建一個package.json文件,內容如下。
~~~
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "4.x"
}
}
~~~
上面代碼定義了項目的名稱、描述、版本等,并且指定需要4.0版本以上的Express。
然后,就可以安裝了。
~~~
$ npm install
~~~
安裝了Express及其依賴的模塊以后,在項目根目錄下,新建一個啟動文件,假定叫做index.js。
~~~
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
~~~
上面代碼運行之后,訪問`http://localhost:8080`,就會在瀏覽器中打開當前目錄的public子目錄。如果public目錄之中有一個圖片文件my_image.png,那么可以用`http://localhost:8080/my_image.png`訪問該文件。
你也可以在index.js之中,生成動態網頁。
~~~
// index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.listen(3000);
~~~
然后,在命令行下運行下面的命令,就可以在瀏覽器中訪問項目網站了。
~~~
$ node index
~~~
默認情況下,網站運行在本機的3000端口,網頁顯示Hello World。
index.js中的`app.get`用于指定不同的訪問路徑所對應的回調函數,這叫做“路由”(routing)。上面代碼只指定了根目錄的回調函數,因此只有一個路由記錄。實際應用中,可能有多個路由記錄。
~~~
// 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);
~~~
這時,最好就把路由放到一個單獨的文件中,比如新建一個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');
});
};
~~~
然后,原來的index.js就變成下面這樣。
~~~
// index.js
var express = require('express');
var app = express();
var routes = require('./routes')(app);
app.listen(3000);
~~~
### 搭建HTTPs服務器
使用Express搭建HTTPs加密服務器,也很簡單。
~~~
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');
~~~
## 運行原理
### 底層:http模塊
Express框架建立在node.js內置的http模塊上。 http模塊生成服務器的原始代碼如下。
~~~
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");
~~~
上面代碼的關鍵是http模塊的createServer方法,表示生成一個HTTP服務器實例。該方法接受一個回調函數,該回調函數的參數,分別為代表HTTP請求和HTTP回應的request對象和response對象。
### 對http模塊的再包裝
Express框架的核心是對http模塊的再包裝。上面的代碼用Express改寫如下。
~~~
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方法的參數,從一個回調函數變成了一個Epress對象的實例。而這個實例使用了use方法,加載了與上一段代碼相同的回調函數。
Express框架等于在http模塊之上,加了一個中間層,而use方法則相當于調用中間件。
### 什么是中間件
簡單說,中間件(middleware)就是處理HTTP請求的函數,用來完成各種特定的任務,比如檢查用戶是否登錄、分析數據、以及其他在需要最終將數據發送給用戶之前完成的任務。它最大的特點就是,一個中間件處理完,再傳遞給下一個中間件。
node.js的內置模塊http的createServer方法,可以生成一個服務器實例,該實例允許在運行過程中,調用一系列函數(也就是中間件)。當一個HTTP請求進入服務器,服務器實例會調用第一個中間件,完成后根據設置,決定是否再調用下一個中間件。中間件內部可以使用服務器實例的response對象(ServerResponse,即回調函數的第二個參數),以及一個next回調函數(即第三個參數)。每個中間件都可以對HTTP請求(request對象)做出回應,并且決定是否調用next方法,將request對象再傳給下一個中間件。
一個不進行任何操作、只傳遞request對象的中間件,大概是下面這樣:
~~~
function uselessMiddleware(req, res, next) {
next();
}
~~~
上面代碼的next為中間件的回調函數。如果它帶有參數,則代表拋出一個錯誤,參數為錯誤文本。
~~~
function uselessMiddleware(req, res, next) {
next('出錯了!');
}
~~~
拋出錯誤以后,后面的中間件將不再執行,直到發現一個錯誤處理函數為止。
### use方法
use是express調用中間件的方法,它返回一個函數。下面是一個連續調用兩個中間件的例子。
~~~
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);
~~~
上面代碼先調用第一個中間件,在控制臺輸出一行信息,然后通過next方法,調用第二個中間件,輸出HTTP回應。由于第二個中間件沒有調用next方法,所以不再request對象就不再向后傳遞了。
使用use方法,可以根據請求的網址,返回不同的網頁內容。
~~~
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);
~~~
上面代碼通過request.url屬性,判斷請求的網址,從而返回不同的內容。
除了在回調函數內部,判斷請求的網址,Express也允許將請求的網址寫在use方法的第一個參數。
~~~
app.use('/', someMiddleware);
~~~
上面代碼表示,只對根目錄的請求,調用某個中間件。
因此,上面的代碼可以寫成下面的樣子。
~~~
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);
~~~
## Express的方法
### all方法和HTTP動詞方法
針對不同的請求,Express提供了use方法的一些別名。比如,上面代碼也可以用別名的形式來寫。
~~~
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方法表示,所有請求都必須通過該中間件,參數中的“*”表示對所有路徑有效。get方法則是只有GET動詞的HTTP請求通過該中間件,它的第一個參數是請求的路徑。由于get方法的回調函數沒有調用next方法,所以只要有一個中間件被調用了,后面的中間件就不會再被調用了。
除了get方法以外,Express還提供post、put、delete方法,即HTTP動詞都是Express的方法。
這些方法的第一個參數,都是請求的路徑。除了絕對匹配以外,Express允許模式匹配。
~~~
app.get("/hello/:who", function(req, res) {
res.end("Hello, " + req.params.who + ".");
});
~~~
上面代碼將匹配“/hello/alice”網址,網址中的alice將被捕獲,作為req.params.who屬性的值。需要注意的是,捕獲后需要對網址進行檢查,過濾不安全字符,上面的寫法只是為了演示,生產中不應這樣直接使用用戶提供的值。
如果在模式參數后面加上問號,表示該參數可選。
~~~
app.get('/hello/:who?',function(req,res) {
if(req.params.id) {
res.end("Hello, " + req.params.who + ".");
}
else {
res.send("Hello, Guest.");
}
});
~~~
下面是一些更復雜的模式匹配的例子。
~~~
app.get('/forum/:fid/thread/:tid', middleware)
// 匹配/commits/71dbb9c
// 或/commits/71dbb9c..4c084f9這樣的git格式的網址
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方法
set方法用于指定變量的值。
~~~
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
~~~
上面代碼使用set方法,為系統變量“views”和“view engine”指定值。
### response對象
(1)response.redirect方法
response.redirect方法允許網址的重定向。
~~~
response.redirect("/hello/anime");
response.redirect("http://www.example.com");
response.redirect(301, "http://www.example.com");
~~~
(2)response.sendFile方法
response.sendFile方法用于發送文件。
~~~
response.sendFile("/path/to/anime.mp4");
~~~
(3)response.render方法
response.render方法用于渲染網頁模板。
~~~
app.get("/", function(request, response) {
response.render("index", { message: "Hello World" });
});
~~~
上面代碼使用render方法,將message變量傳入index模板,渲染成HTML網頁。
### requst對象
(1)request.ip
request.ip屬性用于獲得HTTP請求的IP地址。
(2)request.files
request.files用于獲取上傳的文件。
## 項目開發實例
### 編寫啟動腳本
上一節使用express命令自動建立項目,也可以不使用這個命令,手動新建所有文件。
先建立一個項目目錄(假定這個目錄叫做demo)。進入該目錄,新建一個package.json文件,寫入項目的配置信息。
~~~
{
"name": "demo",
"description": "My First Express App",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
~~~
在項目目錄中,新建文件app.js。項目的代碼就放在這個文件里面。
~~~
var express = require('express');
var app = express();
~~~
上面代碼首先加載express模塊,賦給變量express。然后,生成express實例,賦給變量app。
接著,設定express實例的參數。
~~~
// 設定port變量,意為訪問端口
app.set('port', process.env.PORT || 3000);
// 設定views變量,意為視圖存放的目錄
app.set('views', path.join(__dirname, 'views'));
// 設定view engine變量,意為網頁模板引擎
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);
// 設定靜態文件目錄,比如本地文件
// 目錄為demo/public/images,訪問
// 網址則顯示為http://localhost:3000/images
app.use(express.static(path.join(__dirname, 'public')));
~~~
上面代碼中的set方法用于設定內部變量,use方法用于調用express的中間件。
最后,調用實例方法listen,讓其監聽事先設定的端口(3000)。
~~~
app.listen(app.get('port'));
~~~
這時,運行下面的命令,就可以在瀏覽器訪問[http://127.0.0.1:3000。](http://127.0.0.1:3000%E3%80%82/)
~~~
node app.js
~~~
網頁提示“Cannot GET /”,表示沒有為網站的根路徑指定可以顯示的內容。所以,下一步就是配置路由。
### 配置路由
所謂“路由”,就是指為不同的訪問路徑,指定不同的處理方法。
(1)指定根路徑
在app.js之中,先指定根路徑的處理方法。
~~~
app.get('/', function(req, res) {
res.send('Hello World');
});
~~~
上面代碼的get方法,表示處理客戶端發出的GET請求。相應的,還有app.post、app.put、app.del(delete是JavaScript保留字,所以改叫del)方法。
get方法的第一個參數是訪問路徑,正斜杠(/)就代表根路徑;第二個參數是回調函數,它的req參數表示客戶端發來的HTTP請求,res參數代表發向客戶端的HTTP回應,這兩個參數都是對象。在回調函數內部,使用HTTP回應的send方法,表示向瀏覽器發送一個字符串。然后,運行下面的命令。
~~~
node app.js
~~~
此時,在瀏覽器中訪問[http://127.0.0.1:3000,網頁就會顯示“Hello](http://127.0.0.1:3000%EF%BC%8C%E7%BD%91%E9%A1%B5%E5%B0%B1%E4%BC%9A%E6%98%BE%E7%A4%BA%E2%80%9CHello/)?World”。
如果需要指定HTTP頭信息,回調函數就必須換一種寫法,要使用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)指定特定路徑
上面是處理根目錄的情況,下面再舉一個例子。假定用戶訪問/api路徑,希望返回一個JSON字符串。這時,get可以這樣寫。
~~~
app.get('/api', function(request, response) {
response.send({name:"張三",age:40});
});
~~~
上面代碼表示,除了發送字符串,send方法還可以直接發送對象。重新啟動node以后,再訪問路徑/api,瀏覽器就會顯示一個JSON對象。
~~~
{
"name": "張三",
"age": 40
}
~~~
我們也可以把app.get的回調函數,封裝成模塊。先在routes目錄下面建立一個api.js文件。
~~~
// routes/api.js
exports.index = function (req, res){
res.json(200, {name:"張三",age:40});
}
~~~
然后,在app.js中加載這個模塊。
~~~
// app.js
var api = require('./routes/api');
app.get('/api', api.index);
~~~
現在訪問時,就會顯示與上一次同樣的結果。
如果只向瀏覽器發送簡單的文本信息,上面的方法已經夠用;但是如果要向瀏覽器發送復雜的內容,還是應該使用網頁模板。
### 靜態網頁模板
在項目目錄之中,建立一個子目錄views,用于存放網頁模板。
假定這個項目有三個路徑:根路徑(/)、自我介紹(/about)和文章(/article)。那么,app.js可以這樣寫:
~~~
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);
~~~
上面代碼表示,三個路徑分別對應views目錄中的三個模板:index.html、about.html和article.html。另外,向服務器發送信息的方法,從send變成了sendfile,后者專門用于發送文件。
假定index.html的內容如下:
~~~
<html>
<head>
<title>首頁</title>
</head>
<body>
<h1>Express Demo</h1>
<footer>
<p>
<a href="/">首頁</a> - <a href="/about">自我介紹</a> - <a href="/article">文章</a>
</p>
</footer>
</body>
</html>
~~~
上面代碼是一個靜態網頁。如果想要展示動態內容,就必須使用動態網頁模板。
## 動態網頁模板
網站真正的魅力在于動態網頁,下面我們來看看,如何制作一個動態網頁的網站。
### 安裝模板引擎
Express支持多種模板引擎,這里采用Handlebars模板引擎的服務器端版本[hbs](https://github.com/donpark/hbs)模板引擎。
先安裝hbs。
~~~
npm install hbs --save-dev
~~~
上面代碼將hbs模塊,安裝在項目目錄的子目錄node_modules之中。save-dev參數表示,將依賴關系寫入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"
}
}
~~~
安裝模板引擎之后,就要改寫app.js。
~~~
// app.js文件
var express = require('express');
var app = express();
// 加載hbs模塊
var hbs = require('hbs');
// 指定模板文件的后綴名為html
app.set('view engine', 'html');
// 運行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方法,對網頁模板進行渲染。render方法的參數就是模板的文件名,默認放在子目錄views之中,后綴名已經在前面指定為html,這里可以省略。所以,res.render('index') 就是指,把子目錄views下面的index.html文件,交給模板引擎hbs渲染。
### 新建數據腳本
渲染是指將數據代入模板的過程。實際運用中,數據都是保存在數據庫之中的,這里為了簡化問題,假定數據保存在一個腳本文件中。
在項目目錄中,新建一個文件blog.js,用于存放數據。blog.js的寫法符合CommonJS規范,使得它可以被require語句加載。
~~~
// 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}}
~~~
可以看到,上面三個模板文件都只有網頁主體。因為網頁布局是共享的,所以布局的部分可以單獨新建一個文件layout.html。
~~~
<!-- views/layout.html文件 -->
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{body}}}
<footer>
<p>
<a href="/">首頁</a> - <a href="/about">自我介紹</a>
</p>
</footer>
</body>
</html>
~~~
### 渲染模板
最后,改寫app.js文件。
~~~
// app.js文件
var express = require('express');
var app = express();
var hbs = require('hbs');
// 加載數據模塊
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方法,現在加入了第二個參數,表示模板變量綁定的數據。
現在重啟node服務器,然后訪問[http://127.0.0.1:3000。](http://127.0.0.1:3000%E3%80%82/)
~~~
node app.js
~~~
可以看得,模板已經使用加載的數據渲染成功了。
### 指定靜態文件目錄
模板文件默認存放在views子目錄。這時,如果要在網頁中加載靜態文件(比如樣式表、圖片等),就需要另外指定一個存放靜態文件的目錄。
~~~
app.use(express.static('public'));
~~~
上面代碼在文件app.js之中,指定靜態文件存放的目錄是public。于是,當瀏覽器發出非HTML文件請求時,服務器端就到public目錄尋找這個文件。比如,瀏覽器發出如下的樣式表請求:
~~~
<link href="/bootstrap/css/bootstrap.css" rel="stylesheet">
~~~
服務器端就到public/bootstrap/css/目錄中尋找bootstrap.css文件。
## ExpressJS 4.0的Router用法
Express 4.0的Router用法,做了大幅改變,增加了很多新的功能。Router成了一個單獨的組件,好像小型的express應用程序一樣,有自己的use、get、param和route方法。
### 基本用法
Express 4.0的router對象,需要單獨新建。然后,使用該對象的HTTP動詞方法,為不同的訪問路徑,指定回調函數;最后,掛載到某個路徑
~~~
var router = express.Router();
router.get('/', function(req, res) {
res.send('首頁');
});
router.get('/about', function(req, res) {
res.send('關于');
});
app.use('/', router);
~~~
上面代碼先定義了兩個訪問路徑,然后將它們掛載到根目錄。如果最后一行改為app.use('/app', router),則相當于/app和/app/about這兩個路徑,指定了回調函數。
這種掛載路徑和router對象分離的做法,為程序帶來了更大的靈活性,既可以定義多個router對象,也可以為將同一個router對象掛載到多個路徑。
### router.route方法
router實例對象的route方法,可以接受訪問路徑作為參數。
~~~
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);
~~~
### router中間件
use方法為router對象指定中間件,即在數據正式發給用戶之前,對數據進行處理。下面就是一個中間件的例子。
~~~
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
~~~
上面代碼中,回調函數的next參數,表示接受其他中間件的調用。函數體中的next(),表示將數據傳遞給下一個中間件。
注意,中間件的放置順序很重要,等同于執行順序。而且,中間件必須放在HTTP動詞方法之前,否則不會執行。
### 對路徑參數的處理
router對象的param方法用于路徑參數的處理,可以
~~~
router.param('name', function(req, res, next, name) {
// 對name進行驗證或其他處理……
console.log(name);
req.name = name;
next();
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.name + '!');
});
~~~
上面代碼中,get方法為訪問路徑指定了name參數,param方法則是對name參數進行處理。注意,param方法必須放在HTTP動詞方法之前。
### app.route
假定app是Express的實例對象,Express 4.0為該對象提供了一個route屬性。app.route實際上是express.Router()的縮寫形式,除了直接掛載到根路徑。因此,對同一個路徑指定get和post方法的回調函數,可以寫成鏈式形式。
~~~
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!');
});
~~~
上面代碼的這種寫法,顯然非常簡潔清晰。
## 上傳文件
首先,在網頁插入上傳文件的表單。
~~~
<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>
~~~
然后,服務器腳本建立指向`/upload`目錄的路由。這時可以安裝multer模塊,它提供了上傳文件的許多功能。
~~~
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
// 設定限制,每次最多上傳1個文件,文件大小不超過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發送HTTP請求。
然后,安裝aws-sdk。
~~~
$ npm install aws-sdk --save
~~~
下面是服務器腳本。
~~~
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
~~~
上面代碼中,用戶訪問`/sign`路徑,正確登錄后,會收到一個JSON對象,里面是S3返回的數據和一個暫時用來接收上傳文件的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)
}
~~~
上面代碼首先監聽file控件的change事件,一旦有變化,就先向服務器要求一個臨時的上傳URL,然后向該URL上傳文件。
## 參考鏈接
* Raymond Camden,?[Introduction to Express](http://net.tutsplus.com/tutorials/javascript-ajax/introduction-to-express/)
* Christopher Buecheler,?[Getting Started With Node.js, Express, MongoDB](http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/)
* Stephen Sugden,?[A short guide to Connect Middleware](http://stephensugden.com/middleware_guide/)
* Evan Hahn,?[Understanding Express.js](http://evanhahn.com/understanding-express/)
* Chris Sevilleja,?[Learn to Use the New Router in ExpressJS 4.0](http://scotch.io/tutorials/javascript/learn-to-use-the-new-router-in-expressjs-4)
* Stefan Fidanov,?[Limitless file uploading to Amazon S3 with Node & Express](http://www.terlici.com/2015/05/23/uploading-files-S3.html)
- 第一章 導論
- 1.1 前言
- 1.2 為什么學習JavaScript?
- 1.3 JavaScript的歷史
- 第二章 基本語法
- 2.1 語法概述
- 2.2 數值
- 2.3 字符串
- 2.4 對象
- 2.5 數組
- 2.6 函數
- 2.7 運算符
- 2.8 數據類型轉換
- 2.9 錯誤處理機制
- 2.10 JavaScript 編程風格
- 第三章 標準庫
- 3.1 Object對象
- 3.2 Array 對象
- 3.3 包裝對象和Boolean對象
- 3.4 Number對象
- 3.5 String對象
- 3.6 Math對象
- 3.7 Date對象
- 3.8 RegExp對象
- 3.9 JSON對象
- 3.10 ArrayBuffer:類型化數組
- 第四章 面向對象編程
- 4.1 概述
- 4.2 封裝
- 4.3 繼承
- 4.4 模塊化編程
- 第五章 DOM
- 5.1 Node節點
- 5.2 document節點
- 5.3 Element對象
- 5.4 Text節點和DocumentFragment節點
- 5.5 Event對象
- 5.6 CSS操作
- 5.7 Mutation Observer
- 第六章 瀏覽器對象
- 6.1 瀏覽器的JavaScript引擎
- 6.2 定時器
- 6.3 window對象
- 6.4 history對象
- 6.5 Ajax
- 6.6 同域限制和window.postMessage方法
- 6.7 Web Storage:瀏覽器端數據儲存機制
- 6.8 IndexedDB:瀏覽器端數據庫
- 6.9 Web Notifications API
- 6.10 Performance API
- 6.11 移動設備API
- 第七章 HTML網頁的API
- 7.1 HTML網頁元素
- 7.2 Canvas API
- 7.3 SVG 圖像
- 7.4 表單
- 7.5 文件和二進制數據的操作
- 7.6 Web Worker
- 7.7 SSE:服務器發送事件
- 7.8 Page Visibility API
- 7.9 Fullscreen API:全屏操作
- 7.10 Web Speech
- 7.11 requestAnimationFrame
- 7.12 WebSocket
- 7.13 WebRTC
- 7.14 Web Components
- 第八章 開發工具
- 8.1 console對象
- 8.2 PhantomJS
- 8.3 Bower:客戶端庫管理工具
- 8.4 Grunt:任務自動管理工具
- 8.5 Gulp:任務自動管理工具
- 8.6 Browserify:瀏覽器加載Node.js模塊
- 8.7 RequireJS和AMD規范
- 8.8 Source Map
- 8.9 JavaScript 程序測試
- 第九章 JavaScript高級語法
- 9.1 Promise對象
- 9.2 有限狀態機
- 9.3 MVC框架與Backbone.js
- 9.4 嚴格模式
- 9.5 ECMAScript 6 介紹
- 附錄
- 10.1 JavaScript API列表
- 草稿一:函數庫
- 11.1 Underscore.js
- 11.2 Modernizr
- 11.3 Datejs
- 11.4 D3.js
- 11.5 設計模式
- 11.6 排序算法
- 草稿二:jQuery
- 12.1 jQuery概述
- 12.2 jQuery工具方法
- 12.3 jQuery插件開發
- 12.4 jQuery.Deferred對象
- 12.5 如何做到 jQuery-free?
- 草稿三:Node.js
- 13.1 Node.js 概述
- 13.2 CommonJS規范
- 13.3 package.json文件
- 13.4 npm模塊管理器
- 13.5 fs 模塊
- 13.6 Path模塊
- 13.7 process對象
- 13.8 Buffer對象
- 13.9 Events模塊
- 13.10 stream接口
- 13.11 Child Process模塊
- 13.12 Http模塊
- 13.13 assert 模塊
- 13.14 Cluster模塊
- 13.15 os模塊
- 13.16 Net模塊和DNS模塊
- 13.17 Express框架
- 13.18 Koa 框架