通过 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}`);
});