nodejs的express使用介紹

Express框架

來自《JavaScript 標準參考教程(alpha)》,by 阮一峯javascript

目錄

概述

Express是目前最流行的基於Node.js的Web開發框架,能夠快速地搭建一個完整功能的網站。css

Express上手很是簡單,首先新建一個項目目錄,假定叫作hello-world。html

$ mkdir hello-world

進入該目錄,新建一個package.json文件,內容以下。java

{
  "name": "hello-world",
  "description": "hello world test app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "4.x"
  }
}

上面代碼定義了項目的名稱、描述、版本等,而且指定須要4.0版本以上的Express。node

而後,就能夠安裝了。git

$ npm install

執行上面的命令之後,在項目根目錄下,新建一個啓動文件,假定叫作index.js。github

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

app.use(express.static(__dirname + '/public'));

app.listen(8080);

而後,運行上面的啓動腳本。web

$ node index

如今就能夠訪問http://localhost:8080,它會在瀏覽器中打開當前目錄的public子目錄(嚴格來講,是打開public目錄的index.html文件)。若是public目錄之中有一個圖片文件my_image.png,那麼能夠用http://localhost:8080/my_image.png訪問該文件。ajax

你也能夠在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);

運行原理

底層: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對象。

Express框架的核心是對http模塊的再包裝。上面的代碼用Express改寫以下。

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

app.get('/', function (req, res) {
  res.send('Hello world!');
});

app.listen(3000);

比較兩段代碼,能夠看到它們很是接近。原來是用http.createServer方法新建一個app實例,如今則是用Express的構造方法,生成一個Epress實例。二者的回調函數都是相同的。Express框架等於在http模塊之上,加了一箇中間層。

什麼是中間件

簡單說,中間件(middleware)就是處理HTTP請求的函數。它最大的特色就是,一箇中間件處理完,再傳遞給下一個中間件。App實例在運行過程當中,會調用一系列的中間件。

每一箇中間件能夠從App實例,接收三個參數,依次爲request對象(表明HTTP請求)、response對象(表明HTTP迴應),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);

上面代碼使用app.use方法,註冊了兩個中間件。收到HTTP請求後,先調用第一個中間件,在控制檯輸出一行信息,而後經過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屬性,判斷請求的網址,從而返回不一樣的內容。注意,app.use方法一共登記了三個中間件,只要請求路徑匹配,就不會將執行權交給下一個中間件。所以,最後一箇中間件會返回404錯誤,即前面的中間件都沒匹配請求路徑,找不到所要請求的資源。

除了在回調函數內部判斷請求的網址,use方法也容許將請求網址寫在第一個參數。這表明,只有請求路徑匹配這個參數,後面的中間件纔會生效。無疑,這樣寫更加清晰和方便。

app.use('/path', someMiddleware);

上面代碼表示,只對根目錄的請求,調用某個中間件。

所以,上面的代碼能夠寫成下面的樣子。

var express = require("express");
var http = require("http");

var app = express();

app.use("/home", 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用於獲取上傳的文件。

搭建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');

項目開發實例

編寫啓動腳本

上一節使用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。

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 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模板引擎。

先安裝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。

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文件。

Express.Router用法

從Express 4.0開始,路由器功能成了一個單獨的組件Express.Router。它好像小型的express應用程序同樣,有本身的use、get、param和route方法。

基本用法

首先,Express.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.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上傳文件。

參考連接

 

出處:http://javascript.ruanyifeng.com/nodejs/express.html

相關文章
相關標籤/搜索