萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

在 IIS 上以 iisnode 託管 Node.js 應用程式:安裝與配置完整指南

早期想將部落格從 ASP.NET 遷移至 Node.js + Express,但伺服器環境為 Windows Server + IIS,若兩者同時監聽 80 埠會產生衝突。幸好有 iisnode 這個 IIS 擴充模組,能將 Node.js 程式直接託管在 IIS 內,繼而享有 IIS 內建的進程管理、GZip 壓縮、日誌、快取、權限控制、域名綁定等功能。

先決條件

  1. Node.js(建議安裝 LTS 版本)
  2. URL Rewrite Module(IIS 重寫模組)
  3. iisnode(從 GitHub 下載對應平台的安裝包)

建立站點與核心配置

在 IIS 管理員中新增網站,實體路徑指向 Express 專案根目錄。關鍵在於於專案根目錄新增 web.config,內容如下:

<configuration>
  <system.webServer>
    <handlers>
      <add name="iisnode" path="bin/www" verb="*" modules="iisnode" resourceType="Unspecified" requireAccess="Script" />
    </handlers>

    <rewrite>
      <rules>
        <rule name="all">
          <match url="/*" />
          <action type="Rewrite" url="bin/www" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

上述配置將所有請求重寫至 bin/www(Express 預設啟動腳本),並交由 iisnode 處理。但直接訪問會報錯:

「請求篩選模組被配置為拒絕包含 hiddenSegment 節的 URL 中的路徑」

原因在於 ASP.NET 視 bin 為受保護目錄。解決方法是將目錄重命名(如 launch),並同步修改 web.config 中的路徑。

解決客戶端 IP 丟失問題

Express 透過 req.ip 取得客戶 IP,底層讀取 REMOTE_ADDR 標頭。經 iisnode 轉發後該標頭遺失。官方建議使用 X-Forwarded-For,另可在 web.config 加入:

<iisnode promoteServerVars="REMOTE_ADDR" />

此設定會將 REMOTE_ADDR 重命名為 x-iisnode-REMOTE_ADDR。需在 Express 中以中介軟覆寫 req.ip:

app.use(function(req, res, next) {
  Object.defineProperty(req, 'ip', {
    get: function() { return this.headers['x-iisnode-REMOTE_ADDR']; }
  });
  next();
});

修正靜態檔案上傳路徑

因啟動腳本位於 launch/www,導致工作目錄錯誤,上傳檔案寫入 launch/public/upload 而非專案根目錄。最終採用「根目錄建立 launch.js 引用 bin/www」的做法:

// launch.js
#!/usr/bin/env node
require('./bin/www');

並更新 web.config 指向 launch.js:

<configuration>
  <system.webServer>
    <handlers>
      <add name="iisnode" path="launch.js" verb="*" modules="iisnode" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <rewrite>
      <rules>
        <rule name="all">
          <match url="/*" />
          <action type="Rewrite" url="launch.js" />
        </rule>
      </rules>
    </rewrite>
    <iisnode promoteServerVars="REMOTE_ADDR" />
  </system.webServer>
</configuration>

重啟站點後一切正常。雖然 iisnode 尚未完全成熟,但已足以應對生產環境部署需求。

copyright © 萬盛學電腦網 all rights reserved