AngularJS中的IIS URL重写与angular度HTML5模式的节点

我有一个构build在Azure(IIS)托pipe的Node.JS之上的AngularJS应用程序,并使用HTML5模式。 在我不使用Node.JS的情况下,只使用AngularJS和IIS,我可以重写URL,以便在IIS Web.config中使用以下规则刷新页面不会导致404错误:

<rule name="AngularJSHTML5Mode" stopProcessing="true"> <match url=".*"/> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true"/> </conditions> <action type="Rewrite" url="/"/> </rule> 

但是,在Node.js(使用ExpressJS)上使用Angular时,即使在IIS中使用上述规则,也会在页面刷新时收到“Can not GET / myroute”等错误。 有什么我需要在Server.js或Web.config中configuration不同的规则。

这是我目前在Express中的内容。 我正在使用Express 4:

 // Initialize Express App var app = express(); var listener = app.listen(1337, function () { console.log('Listening on port ' + listener.address().port); //Listening on port 1337 }); app.use(express.static(__dirname + "/public")); 

我明白,页面刷新不应该发生在一个SPA作为一个实践的问题,但他们这样做,我需要解释这一点。

我已经尝试过了,这对我有效:

web.config(site.js是我的节点应用程序的入口点)

 <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <httpErrors existingResponse="PassThrough" /> <iisnode nodeProcessCommandLine="&quot;c:\program files\nodejs\node.exe&quot;" watchedFiles="*.js" interceptor="&quot;%programfiles%\iisnode\interceptor.js&quot;" promoteServerVars="LOGON_USER"/> <handlers> <add name="iisnode" path="site.js" verb="*" modules="iisnode" /> </handlers> <rewrite> <rules> <clear /> <rule name="default"> <match url="/*" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="false" /> <action type="Rewrite" url="site.js" /> </rule> </rules> </rewrite> <security> <requestFiltering> <hiddenSegments> <add segment="node_modules" /> </hiddenSegments> </requestFiltering> </security> </system.webServer> </configuration> 

静态文件服务器在快递+url重写

 app.use(express.static(clientDir)); // for SPA app.get('/*', function(req,res, next){ res.format({ html: function(){ res.sendFile(path.join(clientDir, 'index.html')); }, json: function(){ next(); } }); }); //routes... 

我也试图用虚拟应用程序在iis中实现url重写。 这不起作用。 相反,我不得不在我的节点模块中configuration一条path去除路由的前端部分。

但是,一旦您的应用程序启动,您可以让iis服务于静态文件 。

进一步挖掘,我不需要Webconfiguration。 我有这在我的server.jsbuild立连接到Angular索引文件:

 var app = express(); app.use(express.static(__dirname + "/public")); var listener = app.listen(1337, function () { console.log('Listening on port ' + listener.address().port); //Listening on port 1337 }); 

这部分是关键的,在所有的GET,POST等结束时,我添加了这个作为最后一个function。 它需要是最后的,因为它是一个捕获所有,如果你把它放在一个GET或POST函数之前,它不会看到它是快速的,但一个错误的angular路线,如果你的App.jsconfiguration正确,将路由到主页(不需要):

 // Placed at end for routing non-Express calls/AngularJS refreshes app.use('/*', function (req, res) { res.sendFile(__dirname + '/public/index.html'); });