我有一个基于 Node.JS 构建的 AngularJS 应用程序,该应用程序托管在 Azure (IIS) 中并使用 HTML5 模式。在我不使用 Node.JS 而仅将 AngularJS 与 IIS 结合使用的情况下,我可以使用 IIS Web.config 中的以下规则重写 URL,以便页面刷新不会导致 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 之上使用 Angular(使用 ExpressJS)时,即使在 IIS 中使用上述规则,我也会在页面刷新时收到诸如“Cannot GET/myroute”之类的错误。我需要在 Server.js 中配置某些内容或在 Web.config 中配置不同的规则吗?

这是我目前在 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 是我的 Node 应用程序的入口点)

<?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> 

express+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 重写。这是行不通的。相反,我必须在 Node 模块中配置一条路径以去除路线的前导部分。

但是,您可以拥有 iis serve the static files一旦您的应用程序启动。


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!