nodejs的相關問題2

Express框架

我們可以簡單的搭建一下express的使用


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

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

app.listen(3000);

現在就可以訪問http://localhost:3000,它會在瀏覽器中打開當前目錄的public子目錄(嚴格來說,是打開public目錄的index.html文件)。如果public目錄之中有一個圖片文件myimg.jpg,那麼可以用http://localhost:3000/myimg.jpg訪問該文件。

 

當然你也可以再index.js之中。生成動態網頁

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('Hello world!');
});
app.listen(3000);

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

然後在瀏覽器中輸入
http://localhost:3000/
就能看到界面有Hello world!

啓動index.js的app.get方法,用於指定不同訪問路徑對應的回調函數,這叫做“路由”,上面的代碼只是指定了根目錄的回調函數,因此只有一個路由記錄,實際應用中可能會有多個路由記錄。

比如當我們啓動

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);

然後重新執行腳本node express.js。打開瀏覽器輸入http://localhost:3000/,顯示的是Hello world!

打開瀏覽器輸入http://localhost:3000/customer,顯示的是customer page

打開瀏覽器輸入http://localhost:3000/admin,顯示的是admin page

這樣的話最好把路由都放到一個單獨的文件中,比如新建一個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);

既然這麼簡單,既然我們要使用它就得知道它的原理到底是什麼呢?

運行原理

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");

然後執行這段腳本的時候運行,瀏覽器顯示也是Hello world!

上面代碼的關鍵是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模塊之上,加了一箇中間層。

什麼是中間件

每個中間件可以從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(3000);

上面代碼使用app.use方法,註冊了兩個中間件。收到HTTP請求後,先調用第一個中間件,在控制檯輸出一行信息,然後通過next方法,將執行權傳給第二個中間件,輸出HTTP迴應。由於第二個中間件沒有調用next方法,所以request對象就不再向後傳遞了。

比如我們執行腳本打印結果是:

那麼哪個是第一個哪個是第二個中間件呢?其實就是根據從上到下的順序,誰先誰就是第一個,比如我們換一下順序執行這段代碼


app.use(function (request, response, next) {
    console.log("第二個");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello world!\n");
    next();
});

app.use(function (request, response, next) {
    console.log("In comes a " + request.method + " to " + request.url);
    next();
});

http.createServer(app).listen(3000);

就會發現打印的結果就是:

use方法內部可以對訪問路徑進行判斷,據此就能實現簡單的路由,根據不同的請求網址,返回不同的網頁內容。

pp.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(3000);

上面代碼通過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(3000);

在瀏覽器輸入不同結果效果分別是:

all方法和HTTP動詞方法

針對不同的請求,Express提供了use方法的一些別名。比如,上面代碼也可以用別名的形式來寫。

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

app.all("*", function(request, response, next) {
    console.log("*");
    response.writeHead(200, { "Content-Type": "text/plain" });
    next();
});

app.get("/", function(request, response) {
    console.log("/");
    response.end("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
    console.log("about");
    response.end("Welcome to the about page!");
});

app.get("*", function(request, response) {
    console.log("*");
    response.end("404!");
});

http.createServer(app).listen(3000);

當我們在瀏覽器輸入http://localhost:3000/
打印:
*
/
瀏覽器輸入:http://localhost:3000/about
打印
*
about

上面代碼的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屬性的值。需要注意的是,捕獲後需要對網址進行檢查,過濾不安全字符,上面的寫法只是爲了演示,生產中不應這樣直接使用用戶提供的值。

這裏的alice可以隨便換,但是那個:who是關鍵詞

如果在模式參數後面加上問號,表示該參數可選。

下面是一些更復雜的模式匹配的例子。

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方法用於指定變量的值。

set方法用於指定變量的值。

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

上面代碼使用set方法,爲系統變量“views”和“view engine”指定值。

比如我們現在設置一個屬性

app.get("*", function (request, response) {
    console.log("*");
    response.end("404!");
});
app.set('title', 'My Site');
var title = app.get('title');
console.log(title)
http.createServer(app).listen(3000);

運行腳本打印結果:
My Site

 

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網頁。

 

如果你修改了stf源碼,關閉當前運行的stf,執行命令gulp clean && gulp webpack:build && stf local,修改會生效

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章