通過 appSettings 使用 IIS 虛擬目錄或巢狀應用程式

在 IIS 中使用虛擬目錄或巢狀應用程式是一種常見的方案,很可能是你在使用 IISNode 時要利用的方案。

IISNode 不通過配置直接支援虛擬目錄或巢狀應用程式,因此要實現這一點,我們需要利用 IISNode 的一項功能,該功能不屬於配置,而且知之甚少。具有 Web.config<appSettings> 元素的所有子元素將使用 appSetting 鍵作為屬性新增到 process.env 物件中。

讓我們在 <appSettings> 中建立一個虛擬目錄

<appSettings>
  <add key="virtualDirPath" value="/foo" />
</appSettings>

在我們的 Node.js 應用程式中,我們可以訪問 virtualDirPath 設定

console.log(process.env.virtualDirPath); // prints /foo

現在我們可以使用 <appSettings> 元素進行配置,讓我們利用它並在我們的伺服器程式碼中使用它。

// Access the virtualDirPath appSettings and give it a default value of '/'
// in the event that it doesn't exist or isn't set
var virtualDirPath = process.env.virtualDirPath || '/';

// We also want to make sure that our virtualDirPath 
// always starts with a forward slash
if (!virtualDirPath.startsWith('/', 0))
  virtualDirPath = '/' + virtualDirPath;

// Setup a route at the index of our app    
server.get(virtualDirPath, (req, res) => {
    return res.status(200).send('Hello World');
});

我們也可以將 virtualDirPath 與我們的靜態資源一起使用

// Public Directory
server.use(express.static(path.join(virtualDirPath, 'public')));
// Bower
server.use('/bower_components', express.static(path.join(virtualDirPath, 'bower_components')));

讓我們把所有這些放在一起

const express = require('express');
const server = express();

const port = process.env.PORT || 3000;

// Access the virtualDirPath appSettings and give it a default value of '/'
// in the event that it doesn't exist or isn't set
var virtualDirPath = process.env.virtualDirPath || '/';

// We also want to make sure that our virtualDirPath 
// always starts with a forward slash
if (!virtualDirPath.startsWith('/', 0))
  virtualDirPath = '/' + virtualDirPath;

// Public Directory
server.use(express.static(path.join(virtualDirPath, 'public')));
// Bower
server.use('/bower_components', express.static(path.join(virtualDirPath, 'bower_components')));

// Setup a route at the index of our app    
server.get(virtualDirPath, (req, res) => {
    return res.status(200).send('Hello World');
});

server.listen(port, () => {
    console.log(`Listening on ${port}`);
});