Express.js 中的 res.links() 方法
res.links() 方法用於連線兩個連結,這兩個連結是作為引數的屬性提供的,以填充響應的 Link Http 標頭值。
語法
res.links( links )
例項 1
建立一個名為 "resLinks.js" 的檔案,並複製以下程式碼片段。建立檔案後,使用 "node resLinks.js" 命令執行此程式碼,如下例所示 −
// res.links(links) Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an endpoint
app.get('/api', function(req, res){
res.links({
next: 'https://tutorialspoint.tw?page=1',
middle: 'https://tutorialspoint.tw?page=2',
last: 'https://tutorialspoint.tw?page=3'
});
console.log(res.get('link'));
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求訪問以下端點 − localhost:3000/api
輸出
C:\home
ode>> node resLinks.js Server listening on PORT 3000 <https://tutorialspoint.tw?page=1>; rel="next", <https://tutorialspoint.tw?page=2>; rel="middle", <https://tutorialspoint.tw?page=3>; rel="last"
例項 2
我們來看一下另一個例項。
// res.links(links) Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an endpoint
app.get('/api', function(req, res, next){
res.links({
next: 'https://tutorialspoint.tw?page=1',
middle: 'https://tutorialspoint.tw?page=2',
last: 'https://tutorialspoint.tw?page=3'
});
// Using middleware
next();
})
app.get('/api', function(req, res){
console.log(res.get('link'));
res.send();
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求訪問以下端點 − localhost:3000/api
輸出
C:\home
ode>> node resLinks.js Server listening on PORT 3000 <https://tutorialspoint.tw?page=1>; rel="next", <https://tutorialspoint.tw?page=2>; rel="middle", <https://tutorialspoint.tw?page=3>; rel="last"
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP