使用 Express 的基本 Hello World 示例
要使此示例正常工作,你需要在 IIS 主機上建立 IIS 7/8 應用程式,並將包含 Node.js Web App 的目錄新增為物理目錄。確保你的應用程式/應用程式池標識可以訪問 Node.js 安裝。此示例使用 Node.js 64 位安裝。
專案結構
這是 IISNode / Node.js Web 應用程式的基本專案結構。除了新增 Web.config
之外,它看起來幾乎與任何非 IISNode Web App 相同。
- /app_root
- package.json
- server.js
- Web.config
server.js - Express Application
const express = require('express');
const server = express();
// We need to get the port that IISNode passes into us
// using the PORT environment variable, if it isn't set use a default value
const port = process.env.PORT || 3000;
// Setup a route at the index of our app
server.get('/', (req, res) => {
return res.status(200).send('Hello World');
});
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
配置和 Web.config
Web.config
就像任何其他 IIS Web.config
一樣,除了必須存在以下兩件事,URL <rewrite><rules>
和 IISNode <handler>
。這兩個元素都是 <system.webServer>
元素的子元素。
組態
你可以使用 iisnode.yml
檔案或在 Web.config
中新增 <iisnode>
元素作為 <system.webServer>
的子項來配置 IISNode。這兩種配置都可以相互結合使用,但是在這種情況下,Web.config
需要指定 iisnode.yml
檔案**,而且**任何配置衝突都將取自 iisnode.yml
檔案 。這種配置覆蓋不能以相反的方式發生。
IISNode 處理程式
為了讓 IIS 知道 server.js
包含我們的 Node.js Web App,我們需要明確告訴它。我們可以通過將 IISNode <handler>
新增到 <handlers>
元素來實現。
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
</handlers>
URL 重寫規則
配置的最後一部分是確保進入我們的 IIS 例項的 Node.js 應用程式的流量被定向到 IISNode。如果沒有 URL 重寫規則,我們需要訪問 http://<host>/server.js
訪問我們的應用程式,更糟糕的是,當嘗試請求 server.js
提供的資源時,你將獲得一個知識。這就是 IISNode Web 應用程式需要 URL 重寫的原因。
<rewrite>
<rules>
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<rule name="StaticContent" patternSyntax="Wildcard">
<action type="Rewrite" url="public/{R:0}" logRewrittenUrl="true"/>
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
</conditions>
<match url="*.*"/>
</rule>
<!-- All other URLs are mapped to the Node.js application entry point -->
<rule name="DynamicContent">
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
</conditions>
<action type="Rewrite" url="server.js"/>
</rule>
</rules>
</rewrite>
這是一個適用於此示例的 Web.config
檔案 ,設定為 64 位 Node.js 安裝。
就是這樣,現在訪問你的 IIS 站點並看到你的 Node.js 應用程式正常工作。