简体   繁体   中英

Enabling HTML 5 mode in Angular

I am writing my first SPA in AngularJS but have hit a problem with the routing.

I am trying to enable HTML 5, like this:

.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider.otherwise({
        templateUrl: "/angular/components/booking-system/booking-system-template.html"
    });
})

but I understand that there is some configuration to be done to the server (IIS). Can anyone point me in the direction of instructions on what needs doing? The various stackoverflow posts on the subject are a little unclear.

Thanks, M

I don't think you need to configure your server to make the HTML5 mode working. The only thing you need to do is to add

<base href="/">

to your <head></head> .

Be careful as this configuration is applicable only when the app you're running is at the root of the server(for example ' http://myapp.com/ ').

If you want your app to run in a sub-context eg ' http://myapp.com/subapp ', you need to specify your base href as following: <base href="/subapp">

I hope this solves your problem.

Lukas

If you want html5mode enable,you need make changes on the server side to return your entry point on any URL request. Then angular app will parse URL and load needed page.

Have a loook at this for reference: How to: Configure your server to work with html5Mode https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

You should only need one rule in IIS to get this working if you are using ng-view .

Firstly you will need the IIS Url Rewrite Module .

You then need to setup a rule that redirects all routes back to the entry point so that angular picks it up correctly.

Inside the rewrite rule you want something that looks like this:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

You can edit the web.config directly as well using:

<rule name="Angular Rewrite" enabled="true" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="Rewrite" url="/" />
</rule>

You will also need to make sure the base tag is set in the html

<base href="/">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM