现在的位置: 首页 > 综合 > 正文

Node.js+Express on IIS

2013年05月23日 ⁄ 综合 ⁄ 共 1976字 ⁄ 字号 评论关闭

就是想让node.js的程序跑在iis的意思,参考这篇文章《Hosting express node.js applications in IIS using iisnode》即可。

开始参考的是这篇文章《Installing and Running node.js applications within IIS on Windows - Are you mad?》,其实也讲得很清楚了,只是因为太长,中间讲到

WCAT (WEB CAPACITY ANALYSIS TOOL)去了,我还以为讲完了~~结果把网站一发布,跑不起来,发现需要手动编写web.config来加入handler,OK,原生的node程序跑起来了。结果express下的网站又没跑起来,最终解决后,串起来:

  1. 下载安装node,需要注意的是,下的64位版的node是装到64位的program files路径下的,你需要下32位版的,或者直接下一个node.exe到32位program files目录下,新建一个nodejs文件夹放进去;
  2. 下载安装iisnode,此时如此你的c:\program files(x86)\nodejs\node.exe不存在的话它就会报错退出了,这就是我第一步如此提示的原因,装完后管理员权限执行安装目录下的setupsamples.bat可立即体验下,没必要;
  3. 下载安装url rewrite包,express需要
  4. 将你的node网站发布到iis,比如:http://localhost:8081,应用程序池的.net版本任选,无意义

发布网站后做两件事:

1,将监听的端口改为:process.env.PORT,如在express下:app.set('port',process.env.PORT||3000);这样即能保留iis端口又能让node伺服网站的时候使用自定义的(如3000)端口;

2,在网站根目录下添加web.config文件,加入如下内容:

<configuration>
 <system.webServer>

   <!-- indicates that the hello.js file is a node.js application 
   to be handled by the iisnode module -->

   <handlers>
     <add name="iisnode" path="app.js" verb="*" modules="iisnode" />
   </handlers>
 
    <!-- use URL rewriting to redirect the entire branch of the URL namespace
    to app.js node.js application; for example, the following URLs will 
    all be handled by app.js:

http://localhost/foo


http://localhost/bar

    -->
 
    <rewrite>
      <rules>
        <rule name="main">
          <match url="/*" />
          <action type="Rewrite" url="app.js" />
        </rule>
      </rules>
    </rewrite>
 
    <!-- exclude node_modules directory and subdirectories from serving
    by IIS since these are implementation details of node.js applications -->
    
    <security>
      <requestFiltering>
        <hiddenSegments>
          <add segment="node_modules" />
        </hiddenSegments>
      </requestFiltering>
    </security>    
    
  </system.webServer>
</configuration>

这样,所有/开头的url都由app.js接管,app.js又被注册成了一个http handler,使用iisnode模块,这时候一个标准的express就可以正常跑起来了

 

最后,我还用了angular,正好试一下上述url rewrite会不会把angular的url路由也接管掉,实测不会,如果用angular或其它一些框架来做SPA(单页应用)程序是没问题的,原因应该是这些框架都是用切换hash的方式来路由,github那样完全更改url的来不及测试,有时间加上测试结果

 

P.S. 上面介绍安装配置过程的时候,讲到安装完iisnode后可立即体验一下的那个bat程序可以不干,其实还是建议执行一下的,它会在默认网站下生成一个node虚拟路径,里面有比较丰富的示例和说明,特别是上述web.config文件,里面还有很多可配置的地方,在configuration/readme.htm文件里面有详细的描述,建议执行和详阅。

抱歉!评论已关闭.