AngularJS: UI-Router hash bang routing solution not working

I am currently using Angular version 1.6.4.

To solve the problem hashbang

I was having where my entire url was in this format:

http://localhost:8885/#/hotels/holiday-inn

Mine app.js

including router (with ui-router

):

$urlRouterProvider.otherwise('/');
$locationProvider.hashPrefix('');
$locationProvider.html5Mode(true);

$stateProvider
    .state('index', {
        url: '/',
        templateUrl: 'index.html',
        controller: 'hotelController'
    })
    .state('login', {
        url: '/hotel/:name',
        templateUrl: 'views/hotel.html',
        controller: 'hotelController'
    });

      

My ui-view

is in Index.cshtml

(previously I had everything in _Layout.cshtml

, but moved everything to Index.cshtml

):

<!DOCTYPE html>
<html ng-app="hotelScheduler">
<head>
    <meta charset="utf-8" />
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Application</title>
    <link href="~/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/lib/angular/angular.min.js"></script>
    <script src="~/lib/angular-ui-router/release/angular-ui-router.min.js"></script>
    <script src="~/js/app.js"></script>
    <script src="~/js/hotelController.js"></script>
</head>
<body>
    <div ui-view>
    </div>
</body>
</html>

      

Now I have a problem ... If I access http://localhost:8885/hotel/holiday-inn

, I get 404

.

Why is this happening?

Additional troubleshooting methods:

If I access http://localhost:8885/#/hotel/

, it shows index.html

, not views/hotel.html

and changes the address to http://localhost:8885/#%2Fhotel%2F

. (I understand this is a job otherwise

in routing, but why does it work with the url that hashbang starts with?)

I've asked and looked online and people are suggesting that the rest be done with C # MapRoute

or server side code.

How can I do this through either option? If I did this server side, how would I do it through ASP.Net Core and Visual Studio?

Here's my current one MapRoute

:

app.UseMvc(config =>
{
    config.MapRoute(
        name: "Default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "App", action = "Index" }
    );
});

      

OTHER IMAGE . Based on the comments and https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode I tried to add this code in my web.config for server rewrite :

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

      

But now absolutely all simply redirected to root / home page: localhost:8885/

.

Any help?

+3


source to share


2 answers


$ HTML5 location requires a tag <base>

.

via docs:

If you configure $ location to use html5Mode (history.pushState), you need to specify the base url of the tagged application, or configure $ locationProvider to not require the base tag by passing a definition object with requireBase: false for $ locationProvider.html5Mode ():

https://docs.angularjs.org/error/$location/nobase

Fixed updating your code $locationProvider

:

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

      



And then, within yours <head>

, set yours <base>

accordingly. This is the most common pattern /

, but your application may need to access resources from a different folder.

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

      

Or, if you want to be smart, like https://plnkr.co for bootstrapping Angular plunks:

<head>
  <script>document.write('<base href="' + document.location + '" />');</script>
</head>

      

+1


source


I faced similar problem with AngulaJS SPA, I could solve with the following code:

Startup.cs

app.Use(async (context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }
            })
            .UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List<string> { "index.html" } })
            .UseStaticFiles()
            .UseMvc();

      

Index.html

<base href="/" />

      

and when referring to static files in wwwroot folder use forward slash



<script src="/app.js"></script>
<script src="/app/services/auth.service.js"></script>

      

app.js

$stateProvider
        .state('home', {
            url: '/',
            templateUrl: '/index.html',
            controller: 'HomeController',
            controllerAs: "vm"
        });

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

$urlRouterProvider.otherwise('/stores');

      

url rewrite in web.config no longer works with latest ASP.NET core, you can remove this code from web.config.

if you are using MVC you can try with the following code although I am not

        app.UseStaticFiles()
           .UseMvc(routes =>
           {
               routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}");
               routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" });
           });

      

+1


source







All Articles