Node.js後端開發 - 進階篇 #7 express框架之res對象的常見方法

目錄

一、前言

二、瀏覽中文官網API

三、res(response)對象的一些常見方法

1、res.json([body])

---完整測試代碼

---最終效果

2、res.redirect([status,] path)

---完整測試代碼

---最終效果

3、res.sendFile(path [, options] [, fn])

---完整測試代碼

---最終效果

4、res.status(code)

---完整測試代碼

---最終效果


一、前言

上篇文章我們講到express框架是如何通過express模擬Apache實現靜態資源託管服務的一系列知識點,詳情可見博文:Node.js後端開發 - 進階篇 #6 express框架之通過express模擬Apache實現靜態資源託管服務 這篇文章我們將介紹express框架中res(response)對象的一些常見方法

二、瀏覽中文官網API

我們可以先去 express中文官網:http://www.expressjs.com.cn/ 查看下的api文檔,API參考手冊--->4.x

我們可以看到它有五個對象,點擊我們可以看到它們有很多方法,如下圖:

             

          

三、res(response)對象的一些常見方法

1、res.json([body])

服務器端要向客服端響應json數據的時候,可以直接用res.json,下面是官網的一些介紹

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

The parameter can be any JSON type, including object, array, string, Boolean, or number, and you can also use it to convert other values to JSON, such as null, and undefined (although these are technically not valid JSON).

res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });

---完整測試代碼

//1、加載express模塊
var express = require('express');

//2、創建app對象
var app = express();

app.get('/',function (req, res) {
    res.json({name: 'yyh', age: 22});
});

//3、啓動服務
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最終效果

這個 res.json() 其實和我們的 res.send() 是差不多的,你也可以發送 res.send({ name: 'yyh', age: 22 });  測試查看下,同時我們會發現它們響應的 Response Headers 消息頭幾乎完全一樣

Connection: keep - alive
Content - Length: 23
Content - Type: application / json; charset = utf - 8
Date: Mon, 14 Oct 2019 01: 20: 45 GMT
ETag: W / "17-sVBK6dKTLTgMChflmeoQnyWQees"
X - Powered - By: Express

2、res.redirect([status,] path)

它是服務器端向瀏覽器發送重定向的,express把重定向的一系列操作封裝到了 redirect方法 裏面。

第一個參數可傳可不傳,如果不傳參數它默認爲302。就算我們傳了http狀態碼,我們也不需要傳http狀態消息,因爲對應的http狀態碼,有固定的http狀態消息,它會自動判斷這個狀態碼對應的http狀態消息,然後幫我們添上,省去我們手動去填寫了。

第二個參數path,相當於響應頭裏面那個location所對應的值 

下面這個是官網的一些介紹,詳細可參考官網:http://www.expressjs.com.cn/4x/api.html#res.redirect

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

---完整測試代碼

//1、加載express模塊
var express = require('express');

//2、創建app對象
var app = express();

app.get('/',function (req, res) {
    res.redirect('https://www.baidu.com');
    //res.redirect(301, 'https://www.baidu.com');
});

//3、啓動服務
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最終效果

我們在瀏覽器中輸入地址:http://localhost:3000 ,會發現它直接跳轉到百度了,這裏就不截圖了。然後我們可以查看它的響應消息頭,點擊一下左圖的 view source ,我們會看到右圖中的 狀態碼爲302、location爲百度鏈接

      

另外重定向一般以3開頭,如:301、302等,它默認爲302,我們也可以設置狀態碼爲301看看效果 

res.redirect(301, 'https://www.baidu.com');

HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Location: https://www.baidu.com
Vary: Accept
Content-Type: text/html; charset=utf-8
Content-Length: 98
Date: Mon, 14 Oct 2019 02:05:29 GMT

所以說我們以後在服務器端做重定向的時候,就可以直接調用redirect方法了

3、res.sendFile(path [, options] [, fn])

res.sendFile() is supported by Express v4.8.0 onwards.

Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.

這個方法在express 4.8.0 纔開始有的,不用像以前用fs對象調用它的函數如createReadStream函數來進行一系列的操作,sendFile此方法讀取操作已經給我們封裝好了,我們基本上一句代碼就可以搞定!

官網介紹連接:http://www.expressjs.com.cn/4x/api.html#res.sendFile

---完整測試代碼

步驟1:

在當前項目的public目錄下隨便建立一個文件叫 xxx.txt 然後我輸入內容:nodejs前端、後端開發

步驟2:

使用sendFile方法進行讀取操作,響應給瀏覽器

//1、加載express模塊
var express = require('express');
var path = require('path');

//2、創建app對象
var app = express();

app.get('/',function (req, res) {
    //使用sendFile方法進行讀取操作,響應給瀏覽器
    res.sendFile(path.join(__dirname, 'public', 'xxx.txt'),function (err) {
        if(err){
            throw err;
        }else{
            console.log('ok');
        }
    });
});

//3、啓動服務
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最終效果

瀏覽器得到 sendFile方法讀取 響應的消息

當訪問成功,服務端輸出消息  ok

MacBook-Pro:express-apache luminal$ node app
http://localhost:3000
ok

4、res.status(code)

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');

它是用來設置響應狀態碼的,res.redirect重定向一般以3開頭。如果我想來個404,以前我們響應404顯示文件不存在這幾個字,需要幾行代碼,這裏不需要了,變得更簡單!

res.status(404).send('文件不存在!');

---完整測試代碼

//1、加載express模塊
var express = require('express');
var path = require('path');

//2、創建app對象
var app = express();

app.get('/',function (req, res) {
    res.status(404).send('文件不存在!');
});

//3、啓動服務
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最終效果

我們在瀏覽器中輸入:http://localhost:3000/ ,如下圖

我們也可以查看下它的響應消息頭

HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 18
ETag: W/"12-PAojnk9dJEVQS3m3Y6TXhVfiRvY"
Date: Mon, 14 Oct 2019 03:37:59 GMT
Connection: keep-alive

 

 

 

 

 

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