Express.js – app.set() 方法


app.set() 函式將設定名稱分配或設定為值。這可以按照使用者需要的方式儲存任何型別的變數,但是有一些特定的名稱可以用來配置伺服器的行為

可以使用 set 功能配置的一些屬性為 −

  • env

  • etag

  • jsonp escape

語法

app.set(name, value)

示例 1

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

// app.set() Demo Example

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

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

// Setting the value to name
app.set('title', 'Welcome to TutorialsPoint');

// Creating an endpoint
app.get('/', (req, res) => {
   res.send(app.get('title'));
   console.log(app.get('title'));
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

現在,點選以下端點/api 以呼叫函式

輸出

C:\home
ode>> node appSet.js Server listening on PORT 3000 Welcome to TutorialsPoint

示例 2

我們來看另一個示例。

// app.set() Demo Example

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

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

// Setting the value to name
app.set('title', 'Hi, The requested page is not available');

// Creating an endpoint
app.get('/*', (req, res) => {
   res.send(app.get('title'));
   console.log(app.get('title'));
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

對於上面的函式,你可以在 '/' 後面呼叫任何端點,它只會透過上面的函式傳遞。例如

輸出

C:\home
ode>> node appRoute.js Server listening on PORT 3000 Hi, The requested page is not available

更新日期: 30-Sep-2021

3K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始吧
廣告
© . All rights reserved.