Javascript 如何从 angularjs ng-route 中删除哈希 #

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28629774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:08:34  来源:igfitidea点击:

How to remove the hash # from the angularjs ng-route

javascriptangularjsangular-routing

提问by Apostolos

I am trying to use the locationProvider to remove the hashtag from the url routes in angular js but it gives me error.

我正在尝试使用 locationProvider 从 angular js 中的 url 路由中删除主题标签,但它给了我错误。

app.js

应用程序.js

var eclassApp = angular.module('eclassApp', 
    ['ngRoute', 'eclassControllers', ]
);

eclassApp.config(['$routeProvider','$locationProvider',
    function ($routeProvider, $locationProvider){
        $routeProvider.
            when('/',{
                templateUrl: '/html/student-list.html',
                controller: 'StudentsListCtrl',
            }).
            when('/students/:studentId',{
                templateUrl: '/html/student-details.html',
                controller: 'StudentDetailsCtrl',

            }).otherwise({
                redirectTo: '/students'
            });
            $locationProvider.htmlMode(true);
    }]
);

the error:

错误:

 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=eclassApp&p1=TypeE…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.13%2Fangular.min.js%3A17%3A1)

Am I missing something?

我错过了什么吗?

EDIT: calling the html5Mode function with options object like this

编辑:使用这样的选项对象调用 html5Mode 函数

$locationProvider.html5Mode({
    enabled:true
})

i get the following error (changed to angular full to get a better explanation of the error istead of the minified version)

我收到以下错误(更改为 angular full 以获得对错误的更好解释,而不是缩小版本)

Error: [$location:nobase] $location in HTML5 mode requires a <base> tag to be present!

http://errors.angularjs.org/1.3.13/$location/nobase

http://errors.angularjs.org/1.3.13/$location/nobase

回答by Rabi

you can use the $locationProvider like this -

你可以像这样使用 $locationProvider -

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

Alternatively, you can use the base tag in your index.html (I suppose this is your landing page)

或者,您可以在 index.html 中使用 base 标签(我想这是您的登录页面)

<head>
  <base href="/">
</head>

Removing base tag may cause some side effects in old IE browser like IE9

删除基本标签可能会在旧的 IE 浏览器(如 IE9)中产生一些副作用

回答by Giridhar Kumar

Steps to get rid of # from URL:

从 URL 中删除 # 的步骤:

  1. Inject $locationProviderin config() function of angular root module and set html5Mode() to true

    angular.module( 'app', [ ] ).config(function( $locationProvider) {
       $locationProvider.html5Mode(true);
    });
    
  2. Include basetag in head section of first loading page of application..

  1. 在 angular 根模块的 config() 函数中注入$locationProvider并将 html5Mode() 设置为 true

    angular.module( 'app', [ ] ).config(function( $locationProvider) {
       $locationProvider.html5Mode(true);
    });
    
  2. 在应用程序的第一个加载页面的头部部分包含基本标签。

回答by alpesh

  • Step1: Inject $locationProviderin config()function of angular root module and set html5Mode()to true, syntax is change on angular 1.3version.

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
    
  • Step2: add below settings on web.config

  • 第一步:进样$locationProviderconfig()角根模块和组的功能html5Mode()为true,语法上的变化angular 1.3版本。

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
    
  • 步骤2:添加以下设置web.config



<system.webServer>
  <rewrite>
    <rules>
      <clear />
      <rule name="AngularJS" enabled=true 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_FILENAME}" pattern"^/(api)" negate="true" />
          </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

回答by LOTUSMS

I know this is a year old but I still, to this day, haven't found one concise and full solution to this. It's all bits and pieces from several answers all over the net, so I am going to explain it here in detail and hopefully it could be the one place where other visitors can get one full answer. *I would append to the answer but this is too long to do that. So, let's get started.

我知道这已经一岁了,但直到今天,我仍然没有找到一个简洁而完整的解决方案。这是网络上几个答案的所有点点滴滴,所以我将在这里详细解释它,希望它可以成为其他访问者可以获得完整答案的地方。*我会附加到答案,但这太长了。所以,让我们开始吧。

First you need to download either ngRoute or angular-ui-router. I choose the latter because it already contains all that it's in ngRoute and it still has more features. So why not?

首先,您需要下载 ngRoute 或 angular-ui-router。我选择后者是因为它已经包含了 ngRoute 中的所有内容,并且还有更多功能。那为什么不呢?

  1. Go to your CMD and type this

    npm install --save angular-ui-router
    
  2. Now go to your app.js file and write your routes like this

    var app = angular.module('ngCribs', ['ui.bootstrap', 'ui.router']);
    
    app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
        // Application routes
        $stateProvider
            .state('index', {
                url: '/',
                templateUrl: 'views/partials/home.html'
            })
            .state('listings', {
                url: '/listings',
                templateUrl: 'views/partials/listings-list.html'
            });
    
        // For unmatched routes
        $urlRouterProvider.otherwise('/');
    
        $locationProvider.html5Mode(true);
    
    }]);
    
  3. For your next step, you need to go to your <head>and add your base directory

    <base href="/"> </base>
    
  4. By now, you shouldn't have the hashtag anymore BUT, if you go to any page other than /and reload it, you get an error and the page doesn't load. You need to tell your server how to treat your path and base directory. So to cure this dilemma, you need a server and I prefer Express, but you can use others out there. I recommend Express because at some point you will need to get involved with MEAN stacks and guess what? Other than Mongo, you are already using Angular and Node, so why not add Express to the mix?! Go to your CMD again and do this:

    $ npm install express --save
    
  5. Now that you have a server installed, you must create a server.jsfile and put it in the base of your directory and put the following in it. *ensure your folder paths match your directory so that they're found.

    var express = require('express');
    var server = express();
    
    server.use(express.static(__dirname + '/'));
    server.set('views', __dirname + 'views');
    server.set('js', __dirname + 'js');
    server.set('css', __dirname + 'css');
    
    server.get('/', function(req, res){
        res.render('index.ejs');
    });
    
    server.all('/*', function(req, res, next) {
        // Just send the index.html for other files to support HTML5Mode
        res.sendFile('index.html', { root: __dirname });
    });
    
    //the port you want to use
    var port = 3006;
    server.listen(port, function(){
        console.log('server listening on port' + port)
    });
    
  6. Not done yet. As soon as you try to run the server on port 3006 you will get an error. Back to CMD and type this:

    npm install ejs --save
    
  7. You are done, now you just need to run your server and leave it open. So from this point forward, anything you need to do in the CMD, you will need a second CMD window. (I normally have 4 running at the time. 1-server, 2-Gulp for BrowserSync, 3-MongoDB, 4-To download any dependencies I may need along the way). So go to your CMD and do this to run your server and minimize it out of the way

    node server.js
    
  8. Now, you are free to go to localhost:3006and navigate as if you were in a live server that is already config for you.

  1. 转到您的 CMD 并键入此内容

    npm install --save angular-ui-router
    
  2. 现在转到您的 app.js 文件并像这样编写您的路线

    var app = angular.module('ngCribs', ['ui.bootstrap', 'ui.router']);
    
    app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
        // Application routes
        $stateProvider
            .state('index', {
                url: '/',
                templateUrl: 'views/partials/home.html'
            })
            .state('listings', {
                url: '/listings',
                templateUrl: 'views/partials/listings-list.html'
            });
    
        // For unmatched routes
        $urlRouterProvider.otherwise('/');
    
        $locationProvider.html5Mode(true);
    
    }]);
    
  3. 对于下一步,您需要转到您的<head>并添加您的基本目录

    <base href="/"> </base>
    
  4. 到现在为止,您不应该再拥有主题标签,但是,如果您转到除/重新加载之外的任何页面,则会收到错误消息并且该页面无法加载。您需要告诉您的服务器如何处理您的路径和基本目录。所以为了解决这个困境,你需要一个服务器,我更喜欢 Express,但你可以使用其他服务器。我推荐 Express 因为在某些时候你需要参与到 MEAN 堆栈中,你猜怎么着?除了 Mongo,您已经在使用 Angular 和 Node,那么为什么不添加 Express 呢?!再次转到您的 CMD 并执行以下操作:

    $ npm install express --save
    
  5. 现在您已经安装了服务器,您必须创建一个server.js文件并将其放在您的目录的基础中,并将以下内容放入其中。*确保您的文件夹路径与您的目录匹配,以便找到它们。

    var express = require('express');
    var server = express();
    
    server.use(express.static(__dirname + '/'));
    server.set('views', __dirname + 'views');
    server.set('js', __dirname + 'js');
    server.set('css', __dirname + 'css');
    
    server.get('/', function(req, res){
        res.render('index.ejs');
    });
    
    server.all('/*', function(req, res, next) {
        // Just send the index.html for other files to support HTML5Mode
        res.sendFile('index.html', { root: __dirname });
    });
    
    //the port you want to use
    var port = 3006;
    server.listen(port, function(){
        console.log('server listening on port' + port)
    });
    
  6. 还没做完。一旦您尝试在端口 3006 上运行服务器,您就会收到错误消息。回到 CMD 并输入:

    npm install ejs --save
    
  7. 你已经完成了,现在你只需要运行你的服务器并让它保持打开状态。所以从现在开始,你需要在 CMD 中做的任何事情,你都需要第二个 CMD 窗口。(当时我通常有 4 个在运行。1 个服务器,2 个用于 BrowserSync 的 Gulp,3 个 MongoDB,4 个在此过程中下载我可能需要的任何依赖项)。因此,转到您的 CMD 并执行此操作以运行您的服务器并将其最小化

    node server.js
    
  8. 现在,您可以localhost:3006像在已经为您配置的实时服务器中一样自由地进行导航。

回答by V31

There is an extra comma in dependency array that you have. You can remove the comma as well as include base tag in your head section of the html that you have and you are good with removal of hashtags

您拥有的依赖项数组中有一个额外的逗号。您可以删除逗号并在您拥有的 html 的头部部分包含基本标签,并且您可以删除主题标签

<base href="/">

Your dependency array:

你的依赖数组:

var eclassApp = angular.module('eclassApp', ['ngRoute', 'eclassControllers'] ); 

回答by Luis Teijon

Try this line:

试试这一行:

$locationProvider.hashPrefix('!').html5Mode(true);

$locationProvider.hashPrefix('!').html5Mode(true);

before this line:

在此行之前:

$routeProvider.

$routeProvider.

回答by Raj Malakpet

Tested on Angular 1.6.1 version:

在 Angular 1.6.1 版本上测试:

It requires 3 steps to remove the hashtag (#) from URL.

从 URL 中删除主题标签 (#) 需要 3 个步骤。

Step 1: enable html5mode on locationProvider through Config. sample code:

第一步:通过Config在locationProvider上启用html5mode。示例代码:

app.config(function($locationProvider, $routeProvider){
            $locationProvider.html5Mode(true);
            $routeProvider.when('/', {templateUrl: 'partials/home.html'}).when('/info', {templateUrl: 'partials/info.html'});
        });

Step 2: provide a base hrefattribute in the head section of index.html. This should be placed on top of all script and CSS tags. the hrefattributes defines the relative path of your project. sample code: base href="/demo/". My demo application sits on root directory of Apache web server. If your application is a sub-directory, use: base href="/demo/sub-directory/"or base href="http://localhost/demo/sub-directory/"

第 2 步:hrefindex.html. 这应该放在所有脚本和 CSS 标签之上。这些href属性定义了项目的相对路径。示例代码:base href="/demo/"。我的演示应用程序位于 Apache Web 服务器的根目录中。如果您的应用程序是子目录,请使用:base href="/demo/sub-directory/"base href="http://localhost/demo/sub-directory/"

Step 3: If you're running this AngularJS application on Apache server (Wamp, Mamp etc): from other StackOverflow posts, you should enable url-rewritemodule. As of Apache version 2.2+, this can be achieved by using command: FallbackResource. Sample code: create an .htaccessfile on root directory of Apache server. Add the below command and restart the server. Provide the relative path index.htmlwhich handles the 404 error caused due angular-route functionality. This should solve refresh/accessing deep-url's and all 404 errors.

第 3 步:如果您在 Apache 服务器(Wamp、Mamp 等)上运行此 AngularJS 应用程序:从其他 StackOverflow 帖子中,您应该启用url-rewrite模块。从 Apache 2.2+ 版本开始,这可以通过使用命令来实现:FallbackResource. 示例代码:.htaccess在 Apache 服务器的根目录下创建一个文件。添加以下命令并重新启动服务器。提供index.html处理由于角度路由功能引起的 404 错误的相对路径。这应该可以解决刷新/访问 deep-url 和所有 404 错误。

FallbackResource /demo/sub-directory/index.html