Refreshing the page causes ngRoute to malfunction or results in an unknown route error

I am encountering an issue with my code.

Whenever I refresh the page on localhost:portnumber/home or /todos or /contacts, it crashes ->

showing an error "Cannot GET /home" or /todos or /contacts.

The same problem occurs if I just enter localhost:portnumber/blablabla ->

it shows an error "Cannot GET /blablabla"

but if I enter just localhost:portnumber, it redirects to localhost:portnumber/home which is good!

I need to resolve the refresh problem and the unknown path

My ngRoute code :

angular.module('contactsApp' , ['ngRoute', 'ngMessages'])
/*
    ROUTE configuration
    when href is... do...
*/
.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/contacts', {
            controller: 'listCtrl',
            templateUrl: '/views/list.html'
        })
        .when('/contacts/new', {
            controller: 'newCtrl',
            templateUrl: '/views/new.html'
        })
        .when('/contact/:id', {
            controller: 'editCtrl',
            templateUrl: '/views/edit.html'
        })
        .when('/todos', {
            controller: 'todoCtrl',
            templateUrl: '/views/noteslist.html'
        })
        .when('/home', {
            controller: 'homeCtrl',
            templateUrl: '/views/Home.html'
        })
        .otherwise({redirectTo: '/home'});
    $locationProvider.html5Mode(true);
});

My index.html:

<html ng-app="contactsApp">
<head>

    <base href="/">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="src/css/style.css" type="text/css">
    <link href="src/css/landing-page.css" rel="stylesheet">

    <!-- Bootstrap Core CSS -->
    <link href="src/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

    <!-- Navigation bar -->
    <nav class="navbar navbar-default navbar-fixed-top topnav" role="navigation">
        <div class="container topnav example2">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/home"><img src="images/logo_noback.jpg" alt="My Office" height="40px" width="auto"/></a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right increse-font-17">
                    <li>
                        <a href="home">Home</a>
                    </li>
                    <li>
                        <a href="todos">ToDo</a>
                    </li>
                    <li>
                        <a href="contacts">Contacts</a>
                    </li>
                </ul>
            </div>
        </div>   
    </nav>
    <!-- End Navigation bar -->

    <!-- Changed page contact -->
    <div class="navbar-overlap">
        <div ng-view></div>
    </div> 
    <!-- End Changed page contact -->

    <!-- Sticky footer -->
    <footer class="navbar navbar-default navbar-fixed-bottom topnav footer-backcolor">
        <div class="col-md-12 margin-5">
            <p class="col-md-6 breadcrumb visible-md visible-lg">Copyright &copy; My Office 2016. All Rights Reserved</p>
            <ul class="pull-right breadcrumb visible-md visible-lg">
                    <li><a href="/home">Home</a></li>
                    <li><a href="/todos">Todo</a></li>
                    <li><a href="/contacts">Contacts</a></li>
            </ul>
        </div>
    </footer>
    <!-- End Sticky footer -->

    <script src="src/js/jquery.js"></script>
    <script src="src/js/bootstrap.min.js"></script>
    <script src="lib/angular/angular.min.js"></script>
    <script src="lib/angular/angular-route.min.js"></script>
    <script src="lib/angular/angular-messages.min.js"></script>
    <script src="src/js/app.js"></script>
    <script src="src/js/controller.js"></script>
    <script src="src/js/filters.js"></script> 
    <script src="src/js/derectives.js"></script> 
</body>

Answer №1

Your angular application is not causing the bug; it's due to using html mode for client-side URL rewriting.

If you are using html mode, make sure to also rewrite the URLs on the server side to prevent 404 errors when users refresh the page or manually enter a URL.

This issue has been discussed in relation to a NodeJS server on this question: AngularJS html5mode reloading page

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

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Can React Router be integrated with Material UI tabs?

I have made some changes to the code of the Tabs component in material ui, <AppBar position="static"> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > < ...

The inline variables in CSS transitions are failing to be detected

The CSS transitions are not recognizing the inline variables, or if they are, they are not receiving the correct information. Below is an illustration of how the inline variables are defined in the HTML: <p class="hidden" style="--order ...

Generate a JSON Object array by collecting data from various elements to make it dynamic

Seeking assistance in creating a dynamic array of JSON objects from the values of various elements. Below are some examples of these elements. There are more elements contributing to the JSON values, but I don't want to repeat the same code three time ...

The request for the specified URL is incorrect

When I send an axios request to an Express URL called "getstatus" in my local development environment, everything works fine. However, once the files are uploaded to a server, the URL path still contains "localhost." this.$axios.get('api/getstatus&ap ...

Issue with ChartJs version 2.8.0: The custom tooltip remains visible even when clicking outside the chart canvas or moving the mouse pointer

I am utilizing ChartJs to display a line chart with a custom tooltip that appears upon the click event of the data points. The challenge I am facing is that the custom tooltip remains visible even when the mouse pointer is outside the chart canvas area. ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

Eliminate duplicate entries in typeahead.js by ensuring unique data sources for both prefetch and remote

Currently, I have implemented typeahead.js with both prefetch and remote data sources. You can check out the example here. $(document).ready(function() { var castDirectors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('val ...

What is the best way to upload a file in Node.js using Express and Multer?

When attempting to send a file from the front end to my node js server, I encountered an issue with receiving the file on the back end. Here is the code snippet: <form id="file-upload-form" class="uploader" action="/uploa ...

What are the steps to create a custom progress bar using JavaScript?

I have experience with HTML and CSS. Below is the HTML code: <div id="wrapper"> <ul id="top"> <center><li><a href="#one" class="button">GENERATE</a></li></center> </ul> <div class="box" i ...

"Refreshing UI-View with AngularJS and UI-Router: A Guide on Reloading Your

I am struggling with Angular UI-Router as I am encountering an issue where the state is not being reloaded. Here is a snippet of my code: app.config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvi ...

Determining when the clear button is clicked in a v-select (vue-select) detection strategy

While working on creating a drop-down using v-select, I encountered an issue. After selecting an option, I needed to clear the drop-down and revert the option array back to its initial stage upon clicking the clear button. I attempted various methods such ...

How to retrieve the same value from multiple selections using Vanilla JavaScript and multiple select options?

Why do we consistently receive the same value and index when using the ctl key to select multiple options? document.querySelector('select').addEventListener('change', function(e) { console.log(this.selectedIndex) console.log(e.ta ...

Sending a base64 image of a canvas to a servlet

I have a JavaScript function that uploads HTML5 canvas base64 image data to a servlet. Here is the code: function saveDataURL(a) { var postData = "canvasData="+a; var ajax = new XMLHttpRequest(); ajax.open("POST",'uploadPhoto.cgi',tr ...

When using selenium-python, every attempt to click a button consistently results in an error message

I've been trying to use Python-Selenium binding to click a button, but I haven't had any luck with various selectors so far. I'm currently using Chromedriver. Although I can select an element using elem = driver.find_element(by='xpath& ...

Verify the definition of the checkbox

I'm attempting to determine whether a checkbox is defined and unchecked. When the page loads, my checkbox is disabled and I receive an error indicating that it is undefined. I attempted to create a condition to prevent the error but was unsuccessful. ...

Combining items in JavaScript using a shared key

Is there a way to combine 4 separate arrays of objects into one big object based on the keys inside an object? For example: OUTPUT: What I want to achieve. [ { "bugId": "", "testerId": "", "firstName": "", "lastName": "", "country": " ...

Discovering distinct colors for this loading dots script

Looking for assistance with a 10 loading dots animation script. I'm trying to customize the color of each dot individually, but when I create separate divs for each dot and control their colors in CSS, it causes issues with the animation. If anyone ...

Ways to enable smooth scrolling feature in Safari

I attempted to implement smoothscroll using a polyfill by adding the following code to the bottom of my body tag: <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99a8486869d819a8a9b868585c ...