【问题标题】:Javascript redirects to the wrong URL [duplicate]Javascript 重定向到错误的 URL [重复]
【发布时间】:2020-06-22 14:56:21
【问题描述】:

我正在使用 angularjs,并且我有一个非常基本的应用程序...

let app = angular.module('GHoF', [
  'ngRoute'
]);

app.config(function Config($routeProvider) {

  // Routes

  console.log($routeProvider);
  $routeProvider
    .when('/applications', {
      templateUrl: 'app/pages/myApplications/myApplications.html',
      controller: 'MyApplicationsCtrl'
    })
    .otherwise({
      redirectTo: 'app/pages/auth.html'
     })

});

HTML

<html lang="en" ng-app="GHoF">
<head>
    <script src="node_modules/angular/angular.js"></script>
    <script src="node_modules/angular-route/angular-route.js"></script>
    <script src="app/app.js"></script>
    <title>Home</title>
</head>
<body>
    <main ng-view></main>
</body>

问题在于它将我重定向到错误的 URL。

http://127.0.0.1:8080/#!/app/pages/auth.html

我不知道为什么,但它在 URL 中显示为 /#!。这是一个非常基本的应用程序...

【问题讨论】:

标签: javascript angularjs ngroute


【解决方案1】:

您需要启用 HTML5Mode 才能摆脱 hashbangs。首先你需要在你的索引文件中添加基本的href(我通常把它直接放在开头的&lt;head&gt;标签下):

<base href="/">

然后在您的配置中,您应该通过 $locationProvider 启用它:

app.config(function Config($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/applications', {
      templateUrl: '/app/pages/myApplications/myApplications.html',
      controller: 'MyApplicationsCtrl'
    })
    .otherwise({
      redirectTo: '/app/pages/auth.html'
    })
});

如果您打算在 HTML5 模式下直接访问这些路由,请不要忘记您需要处理服务器重写。

这是有关如何为不同服务器执行此操作的信息的好资源:https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

【讨论】:

  • 它可以工作,但它现在没有重定向......
  • 我认为redirectTo: 'app/pages/auth.html' 需要一个前导斜杠来从根重定向。如果 /app 已经是您的根目录,请尝试 redirectTo: '/app/pages/auth.html' 甚至 redirectTo: '/pages/auth.html'
  • 它没有重定向...我去http://127.0.0.1:8080/applications并说Cannot GET /applications
  • 如果您要直接访问该 URL,则需要将重写添加到您的服务器。见:riptutorial.com/angularjs/example/21798/…
  • @user12361681我用更好的链接更新了我的答案,以防你不使用 apache
猜你喜欢
  • 2021-07-19
  • 2020-07-07
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
相关资源
最近更新 更多