【问题标题】:Angular ngRoute redirecting to malformed URLAngular ngRoute 重定向到格式错误的 URL
【发布时间】:2017-04-29 07:27:33
【问题描述】:

我正在使用 AngularJS 编写一个 SPA 产品,由 Express 使用 NodeJS 提供服务。 NodeJS/Express 还提供了 SPA 的 API。在生产中,SPA 将位于代理(Apache,或者将来可能是 nginx)后面 - 即使没有代理,也存在以下问题。 ngRoute 用于提供路由。

我最初是在本地测试应用程序,并且一切正常。我将 repo 克隆到测试服务器,但由于某种原因,当我尝试使用该应用程序时,URL 格式不正确。

通常,当页面加载时,应用程序重定向到localhost:8080/#/homehome 是包罗万象的路由)。但是,在测试服务器上时,它会重定向到 domain.com/#!/home#%2Fhome

如果我点击应该将 URL 更改为 domain.com/#/quotations 的链接(href 设置为相对,而不是绝对),我会得到 domain.com/#!/home#%2Fquotations

我的路由器配置:

app.config(['$routeProvider', function($routeProvider){
    // Routes
    $routeProvider
    .when('/home', {
        templateUrl: '/views/home/home.html'
    })
    .when('/staff', {
        templateUrl: '/module/staff/views/staff.html',
        controller: 'staffController',
        controllerAs: 'staff'
    })
    .when('/error', {
        templateUrl: '/views/error/error.html',
        css: '/views/error/error.css'
    })
    .otherwise({
        redirectTo: '/home'
    });
}]);

在我的主要 NodeJS 服务器文件中,我仅使用 web.use(Express.static('public_html')) 将 Express 设置为提供包含 SPA 的文件夹 public_html

我尝试将<base href="/"> 添加到我的 index.html 的头部,但这并没有什么不同。 Angular 和 Express 都没有配置为执行任何不同的操作(与默认设置不同)来重写页面 URL,所以我对问题所在感到非常困惑。

【问题讨论】:

  • 您是否有可能在测试服务器和本地服务器中使用两个不同的 Angular 库?我看到 ! 字符是 1.6

标签: javascript angularjs node.js express ngroute


【解决方案1】:

在 Angular 1.6 中 $location 现在添加了一个“!”如果你想删除它,你可以这样做:

appModule.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

检查这个问题,可能会有所帮助...Angular web app having extra ! in the url

【讨论】:

    【解决方案2】:

    根据您的路由,您应该在 head 标记中使用 <base href="@Url.Content("~/")" />,并在生产中的路由配置中使用 $locationProvider.html5Mode(true); 从 url 中删除 #

    这将解决问题,如果可行,您可以随时恢复基于角度的 url 格式以使用 #

    另一种选择是在您的节点配置中使用此代码:

    <VirtualHost *:80>
      DocumentRoot "/public_html"
      ServerName domain.com
      ServerAlias www.domain.com
    </VirtualHost>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-08
      • 2016-05-24
      • 2014-07-31
      • 2021-07-19
      • 2020-07-07
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多