Using Angular routing with html5mode on an ASP.NET backend allows for

My AngularJS application is based on an ASP.NET project and uses html5mode, which works perfectly fine unless I try to pass route parameter(s).

Here is the Angular routing code:

 $locationProvider.html5Mode(true);

 $routeProvider.when('/accounts', {
            templateUrl: 'templates/accounts.html',
            controller: 'accountsCtrl',
            title: 'Accounts',
            resolve: {
                accounts: function (accountData) {
                    return accountData.getAll();
                }
            }
        });

        $routeProvider.when('/account/:accId', {
            templateUrl: 'templates/editAccount.html',
            controller: 'editAccountCtrl',
            title: 'Account',
            resolve: {
                account: function ($route, accountData) {
                    return accountData.get($route.current.pathParams.accId);
                }
            }
        });

Regarding the web.config file:

<system.webServer>
    <rewrite>
      <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
          <match url="^index\.html" ignoreCase="false" />
          <action type="None" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
          <match url="." ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />

        </rule>
      </rules>
    </rewrite>
  </system.webServer>

When I use the route localhost:3849/accounts, it works. However, when I try localhost:3849/account/1, it breaks the system and fails to load *.js libraries or any other resources.

The console shows an error for every library: Uncaught SyntaxError: Unexpected token <. What could be wrong?

UPDATE: The issue was with how scripts were referenced in the index.html file. Originally, it was:

<script type="text/javascript" src="Scripts/angular.min.js"></script>

It should have been:

<script type="text/javascript" src="/Scripts/angular.min.js"></script>

So, when making a request to localhost:3849/account/1, the server was looking for files at localhost:3849/account instead of finding them and returning index.html. The same issue occurred with routing where:

templateUrl: 'templates/editAccount.html',

Should have been:

templateUrl: '/templates/editAccount.html',

Answer №1

Consider using this alternative approach (adjust the path to index.html accordingly):

<?xml version="1.0" encoding="utf-8"?>

<!--
  To find out more about configuring your ASP.NET application, please check out
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>

  <system.webServer>
  <rewrite>
    <rules>
      <rule name="AngularJS" 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="../index.html" />
      </rule>
    </rules>
  </rewrite>

</system.webServer>


</configuration>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information to the parent component via props

I am facing an issue where I need to utilize a value generated within a function in the child.js file and then pass it to parent.js in order to filter an array of children based on this value. Child.js const returnDistance = () => { const ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Apply a specific image layout once the drop event occurs

I have a container with 5 image pieces that need to be dropped into another container to complete the image. Once an image is dropped, I want to apply the style "position:absolute" so that it sticks to the previous image in that container. Although I have ...

Is there a way to reset an object's prototype in typescript after fetching it from local storage?

In my TypeScript class, there is a method called getTotal() defined on the prototype. class Score { roundOne: any; roundTwo: any; roundThree: any; roundFour: any; roundFive: any; roundSix: any; roundSeven: any; getTotal() { ...

Conceal an item if the span element encompasses a div with a specific class

I am struggling with a problem where I need to hide an "i" element only if a "span" contains a "div" element. The content inside the "span" is loaded via AJAX and rendered as HTML, so it may contain the "div class=difference" or not. The code snippet in q ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

The Iframe is loading a JavaScript that is already loaded on the parent page but is not being fetched from the disk cache

My webpage has 4 iframes, all loading the same javascript file. However, when I checked the network tab in my browser's developer tools, I noticed that the javascript was being loaded 5 times from the server. I tried to set the iframes to load only af ...

What could be the reason for GridView failing to display data when the Paging Index has changed?

I am facing an issue with my GridView in which specific data and records are displayed upon clicking the Generate button. https://i.sstatic.net/FIm5j.png The problem arises when I navigate to the next page of the GridView list, the actual data is not los ...

Exploring datepicker options for my React Project - Determining the top choice for a datepicker

Uncertain if this is the most suitable place to pose this query. In the midst of developing a React website. Date input fields are essential for my project. Attempting to find a user-friendly method for date input. Possibly considering four options: ...

"Creating Interactive Slider Bullets: A Guide to Linking them to Their Respective

I can't seem to figure out how to connect my slider bullets to my slider slides. I want bullet 1 to correspond to slide 1, bullet 2 to slide 2, and so on. It should be a simple task, but I'm struggling to make it work. I have set up a basic reset ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

Create a solution that is compatible with both web browsers and Node.js

I am developing a versatile library that can be utilized in both the browser and in node environment. The project involves three json config files, with the latter two extending the tsconfig.json. tsconfig.json (contains build files) tsconfig.browser.js ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

PHP's 'include' function is now being ported into modern Javascript as a new method

As the library of JS frameworks continues to expand, I'm wondering if there is a simple JS replacement or alternative for PHP's 'include' function. Is PHP include still a relevant method for including chunks of code, or are there better ...

Resolving Problems with setInterval in jQuery Ajax Calls on Chrome

Seeking assistance in returning the value of a specific URL periodically using jQuery and setInterval. Below is my current code snippet: $("form").submit(function() { setInterval(function(){ $('#upload_progress').load(&ap ...

Is there a way to make this animation activate when the entire area in front of the link is hovered over or tapped?

I am working on an animation that needs to run behind a link. Here is an example: https://codepen.io/ehbehr/pen/KKNbOvN and below is the HTML and CSS: *, *:before, *:after { margin: 0; padding: 0; } .container { position: relative; width: 100%; ...

What is the simplest method for finding the position of a child element in relation to its parent?

My HTML markup is structured similarly to this: <div id="parentElement"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div ...