Tips for restructuring website links on IIS without using the pound sign in combination with AngularJS

By utilizing a URL rewrite in my web.config file, I have enabled the ability to insert URLs that do not contain a # symbol. This allows me to access URLs like , using "name" as a parameter to fetch a template file. Whenever this parameter is used with an XMLHTTPRequest, the pages consistently return a 200 response due to validation by the web.config rewrite. Is there a method to establish routes in Angular that will deliver the correct template regardless of whether a file exists or not, and if it doesn't, present a custom 404 page? Currently, on the homepage of my website, a template file is included which exhibits a header ng-view followed by a footer. When accessing a page such as and "random" does not correspond to an existing page, the homepage continues to load without displaying a 404 error page. The page persists to load endlessly.

========== Configuration in web.config ==============

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

======= Angular Routing Settings ===============

angular.module('main').config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider)
{
    //The use of services or factories is restricted so we are unable to utilize 
    //the angular $http provider. Instead, we rely on legacy HTTP AJAX requests
    //to check the status of a given page.

    var checkUrlStatus = function(url){
        console.log(url + '.asp');
        var http = new XMLHttpRequest();
        http.open('GET', url, false);
        http.send();
        console.log(http.status);
        return (http.status !== 404 ? url : 'https://somewebsite.com/404.asp');
    }

    
    //Eliminating hashes from URLs, must be utilized alongside the web.config or apache config file
    if(window.history && window.history.pushState){
    $locationProvider.html5Mode({
        enabled: true, 
       requireBase: false 
     });
         }
         
    //Determines conditions for routing to the appropriate template. Checks if the template 
    //returns the correct response using the checkUrl function before proceeding.
 $routeProvider.when('/:param',{

         templateUrl: function(params){
                //return checkUrlStatus('https://somewebsite.com/pages/accounting.asp');    
             console.log(checkUrlStatus('https://somewebsite.com/pages/bob.asp')    );
            //return "/pages/"+url_param+".asp"; 
         }
     }).when('/',{
     templateUrl: function(){
         return 'home.asp';
     }

 }).otherwise({
     templateUrl: function(){
         return 'home.asp';

     }
 })     

}   

]);

Answer №1

One issue I encountered was when sending a request to a page, it would always return a 200 status code because the URL rewrite was directing it to the home page of my app. To address this, I implemented a solution by adding a "is-content" tag as the first class on the page. When an AJAX request was made for the page, I checked for the presence of this class. If it existed, I displayed the template contents, otherwise I showed the content for my custom 404 page. Below is a snippet of the function I used to handle this scenario:

const checkUrlStatus = (url) => {
        const http = new XMLHttpRequest();
        http.open('GET', url, false);
        http.send();
        const responseText = http.responseText; 
        const htmlObject = document.createElement('div');
        htmlObject.innerHTML = responseText; 
        const htmlReturn = htmlObject;
        if (htmlReturn.getElementsByClassName('is-content').length > 0){
            return url; 
        } else { 
            return 'https://testwebsite.com/pages/404.asp'; 
        }
    }

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

Display the razor page in a modal dialog box

I want to display a razor page within a modal dialog: Here is the code for the razor page: <div class="container"> <div class="title modal " tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static"> < ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Connecting Node.js streams with dynamic logic during execution

After spending the last 6 months working with Node.js streams, I have found them to be incredibly useful and effective. Whenever I encounter a problem, I am able to solve it using the standard formula: A.pipe(B).pipe(C); However, my current challenge inv ...

Can we avoid the error callback of an AJAX request from being triggered once we have aborted the request?

Initially, I encountered a challenge where I needed to find a way to halt an AJAX request automatically if the user decided to navigate away from the page during the request. After some research, I came across this helpful solution on Stack Overflow which ...

What possible reasons could cause an API request to result in an empty array being returned?

I recently encountered an issue when calling this API using npm request. The response I receive is an empty array, despite having loaded request, defined the content value at the top of the page (not displayed here), and modified the API key. Surprisingly, ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

Chosen option - Selection Menu - Relational Database Language

I am currently working on a dropdown list that needs to be filled from a database: <TH> <FORM> <p>Department</p> <SELECT size="1" id="depart"> <OPTION> <?php ...

Leveraging client-side routes in conjunction with page templates retrieved from Contentful

Objective In an effort to restrict access to certain content under a specific URL (/dashboard), I am exploring the use of client-only routes. This content, sourced from Contentful and utilizing a page template, will follow a route structure like {MYDOMAIN ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

How can I show the unique phrase "Today" on a specific date (date=today) with the Angular-UI-Bootstrap Datepicker?

I'm currently integrating the Angular-UI datepicker directive into my project and I'm facing an issue. I want to have the datepicker display 'Today' instead of the actual date like 2015/04/27. Is there a way to achieve this without hav ...

Having trouble retrieving mobiscroll instance in Angular with Ionic

I'm facing an issue with accessing the instance of my mobiscroll widget in Angular 4 with Ionic Framework. Despite following all the correct steps, the actual widget won't get selected. Below is the code for the widget: <mbsc-widget [options ...

Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart. The project includes various categories with different products within each category. When adding a product to the cart from one category, it displays correctly. Likewise, adding anot ...

Detection of the page rendering time for an angular spa application's final section

Our team is working with an angular SPA and we are seeking a solution to generate an event once a page has finished rendering and all ajax calls have been completed. We are open to any suggestions on how we can achieve this without having to implement it ...

Obtain JavaScript object from WebView in Swift

Currently, I am displaying a webView in my iOS app using Swift. My goal is to retrieve an object from the JavaScript code within the webView. Upon inspecting the console, I discovered that the desired object is named "window.user". However, when attempti ...

Dealing with Errors When Working with Angular Promises

Currently, I am in the process of mastering promises within Angular. In my code snippet, I have two "GET" requests that I need to execute sequentially. Everything is functioning properly, but I'm unsure about how to handle errors in this scenario. If ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

Implementing a Custom Callback for JSONP Requests in Angular Services

Utilizing JSONP feeds with custom callback functions is my current task, for instance from this source: jsonpCallbackAllStar2015({ "events": [ { "title": "XYZ" } ... ] }) To achieve this, I followed a helpful g ...

unable to locate text within tag a using javascript

I developed JavaScript code to search for tags within an accordion. function tagSearch(){ let keyword = document.getElementById('find').value.toUpperCase(); let items = document.querySelectorAll('.accordion'); let links = document ...

Utilizing Highcharts to visualize data from a mysql database through a dynamic Pie Chart

I am currently working on generating a pie chart using highcharts to visualize the distribution of each value assigned to a specific column (TYP_CODE) relative to the total number of entries. synthese.php : <?php session_start(); if(!isset($_S ...