DIV CSS 佈局教程網

在 IIS 上運行 Node.js 的 iisnode 安裝配置筆記
編輯:JavaScript綜合知識     

如果你打算在 Windows Server + IIS 的環境上部署 Node.js 應用,iisnode 就是一個好用的擴充。它能讓 Node.js 程式託管到 IIS,託管之後還能免費享有 IIS 的進程管理、GZip 壓縮、日誌、快取、權限控制、域名綁定等種種功能。本文記錄完整的安裝與踩坑過程。

安裝前的準備

要使用 iisnode,需先安裝三樣東西:

1. Node.js
2. IIS 的 URL Rewrite 模組
3. iisnode

建立站點與 web.config

裝好後,在 IIS 管理員中建立站點並指向程式目錄,關鍵是新增一個 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,並用 iisnode 擴充來運行它。然而打開站點後卻出現了錯誤:請求篩選模組被配置為拒絕包含 hiddenSegment 段的 URL 中的路徑。原來,ASP.NET 中的 bin 目錄是不允許存取的隱藏目錄,重寫到 bin/www 恰好命中了這條規則。解法是把目錄改名,例如改成 launch:

代碼如下:
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="launch/www" verb="*" modules="iisnode" resourceType="Unspecified" requireAccess="Script" />
</handlers>
<rewrite>
<rules>
<rule name="all">
<match url="/*" />
<action type="Rewrite" url="launch/www" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

重啟站點後終於能運行起來。但測試時又發現,取得的 IP 為空。在 Express 中 IP 透過 req.ip 取得,而它又源自請求標頭的 REMOTE_ADDR,結果這段標頭在 IIS 到 Node.js 的過程中遺失了。iisnode 確有此問題,解法是在 web.config 中加入:

代碼如下:
<iisnode promoteServerVars="REMOTE_ADDR" />

保留後的 REMOTE_ADDR 會被改名為 x-iisnode-REMOTE_ADDR,因此還得在 app.js 中重新定義 req.ip。由於 Express 的 req.ip 是透過 getter 定義的,需要用 Object.defineProperty 覆寫:

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

接著又發現另一個問題:作為程式入口的 www 位於 launch 目錄,導致 launch 成了應用的執行目錄,於是檔案上傳會存到錯誤的位置。解法是把目錄名改回 bin,並在根目錄建立一個 launch.js 去呼叫 bin/www:

代碼如下:
#!/usr/bin/env node
require('./bin/www');

然後把程式入口改為 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 與 Node.js 都還不是完全成熟的產品,還有許多值得進一步探索與完善的地方。希望這份筆記能幫你在 IIS 上少踩一些坑。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved