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.