Express.js 中的`res.locals` 屬性


res.locals 是一個包含響應區域性變數的物件,這些變數僅作用於請求,因此僅對該請求或響應週期期間呈現的檢視可用。

此屬性在公開請求級資訊(如請求路徑名、使用者設定、已驗證使用者等)時很有用。

語法

res.locals

示例 1

建立一個名為 "resLocals.js" 的檔案,並複製以下程式碼片段。建立檔案後,使用命令 "node resLocals.js" 執行此程式碼,如下例所示 −

// res.locals Property 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.locals = 'Welcome to TutorialsPoint';
   console.log(res.locals);
   res.end(res.locals);
});
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 resLocals.js Server listening on PORT 3000 Welcome to TutorialsPoint

示例 2

我們再看一個示例。

// res.locals Property 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) {

   // Defininf multiple locals
   res.locals.name = 'Mayank';
   res.locals.age = 21;
   res.locals.gender = 'Male'
   console.log(res.locals);
   res.send(res.locals);
});
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 resLocals.js Server listening on PORT 3000 [Object: null prototype] { name: 'Mayank', age: 21, gender: 'Male' }

更新於: 2022-01-29

7K+ 瀏覽量

開啟 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.