Tomcat/Angular Windows 上的应用与 Linux 和尾部斜杠

Tomcat/Angular app on Windows vs Linux and trailing slash

我有一个问题,我不确定是否与 angular 或我的服务器 (tomcat 7) 有关。

到目前为止,我一直在我的本地机器上进行开发,这是一个 Windows 盒子,到目前为止,我已经能够成功部署和 运行 我的 webapp,没有任何问题。我通过转到 URL 访问该站点:http://localhost:8080/appname

现在,我的 angular 应用程序的 $stateProvider 正确加载了默认状态(因此 URL 变为 http://localhost:8080/appname/#/login)。

我现在部署到我们的测试环境,这是一台 linux 机器(与 tomcat7 相同)。当我现在去 URL: http://test-box:8080/appname 它改为:http://test-box:8080/appname#/

请注意 "appname" 后缺少的尾部斜杠。仅加载空白页。我不知道问题出在哪里,tomcat 或 angular,虽然我倾向于后者。

所以我一直没弄清楚为什么这只发生在我的测试环境中,但我确实设法解决了这个问题。我做了以下事情:

  1. 为 angular 应用启用 html5 模式:

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: true
    });
    

    我将 requireBase 设置为 'true' 因为正如我上面提到的,webapp 有一个 appName,这使我指向第 2 点。

  2. 为确保您的 angular 应用程序可以使用您的基本应用程序名称,请将其添加到您的主 index.html 文件中:

    <base href="/appName/">
    

    确保这是在 <head> 标签的顶部完成的

  3. 以上解决了我的问题,但引入了一个新问题。由于 html5 模式,您将不会再在 URL 中看到 #。而现在当你刷新页面时,因为 URL 现在完全由 angular 管理,服务器可能不知道如何处理你试图访问的资源。它甚至可能不存在于服务器端,你会得到一个 404。因此,如果你刷新页面并尝试访问服务器不知道的任何内容(在我的例子中,任何以 appName/api 开头的内容, appName/resourc,等等都可以)它应该被重定向到 index.html。这意味着您将需要重写您的 URL。可惜tomcat7不支持这个,只好升级到tomcat8。 URL重写也可以配置在apache前端服务器上。如果您能够做到这一点,请在 tomcat8 中启用 URL 重写 conf/server.xml:

    <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">
    
        <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    

    然后创建一个名为 conf/rewrite.config 的新文件,其中包含:

    RewriteCond %{REQUEST_URI} ^/appName/(api|resource).*$
    
    RewriteRule ^.*$ - [L]
    RewriteRule ^.*$ /appName/index.html [L,QSA]
    

    这表示任何以 api/*resource/* 开头的内容都可以,其他所有内容都必须重定向到 index.html