Express.js - app.locals 屬性


app.locals 物件定義應用程式內部作為區域性變數的屬性。一旦設定了 app.locals 屬性的值,它將在應用程式的整個生命週期內保持存在。res.locals 屬性僅在請求生命週期內有效。

語法

app.locals

示例 1

建立一個檔案 "appLocals.js",並複製以下程式碼片段。建立檔案後,使用 "node appLocals.js" 命令來執行此程式碼。

// app.locals code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Setting the below email throught out the application
app.locals.email = 'hi@tutorialspoint.com'

console.log("Email Configured is: ", app.locals.email);

輸出

C:\home
ode>> node appLocals.js Email Configured is: hi@tutorialspoint.com

示例 2

我們來看另一個示例。

// app.locals code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Setting the multiple variables throughout the application
app.locals.domain = 'www.tutorialspoint.com'
app.locals.age = '30'
app.locals.company = 'Tutorials Point Ltd'

console.log(app.locals);

輸出

C:\home
ode>> node appLocals.js [Object: null prototype] {    settings:       { 'x-powered-by': true,          etag: 'weak',         'etag fn': [Function: generateETag],          env: 'development',         'query parser': 'extended',         'query parser fn': [Function: parseExtendedQueryString],         'subdomain offset': 2,         'trust proxy': false,         'trust proxy fn': [Function: trustNone],          view: [Function: View],          views: '/home/mayankaggarwal/mysql-test/views',         'jsonp callback name': 'callback' },       domain: 'www.tutorialspoint.com',       age: '30',       company: 'Tutorials Point Ltd' }

更新時間: 2021 年 9 月 30 日

1K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.