Unable to refresh page in Angular without hashtag is causing issues

My web application is built using Spring, Angular, and Rest. I successfully removed the hashtag from the URL by implementing the following code:

if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}

in index.html

 <base href="/webapptest/">

Now, the home page looks good and everything is working perfectly. The URL appears like this:

http://localhost:8080/webapptest/

The issue arises when I try to navigate to the second page after removing the hashtag, causing a 404 error upon reloading. I suspect it may be a server-side problem due to changing the URL structure, but I'm unsure about what needs to be adjusted.

This is my Spring Controller:

@RestController
@RequestMapping(value="api/files")
public class FileController {

@RequestMapping( method = RequestMethod.GET)
public @ResponseBody() String getFile(HttpServletRequest request) throws IOException  {
    String htmlString = "";
    try {....
 ...
return htmlString;
}

The same controller and method are used for both the homepage and page2. Any suggestions on how to resolve the issue of reloading the page without the hashtag?

app.js :

uploadFile.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$routeProvider
    .when('/', {
        templateUrl : 'resources/html/home.html',
        controller : 'uploadFileController'
    })
    .when('/page2', {
        templateUrl : 'resources/html/page2.html',
        controller : 'uploadFileControllerAdmin'
    })
    .otherwise({
        redirectTo: '/'
    });
if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}
}])

Answer №1

When the initial request is made to /webapptest, the server (e.g. Spring App) responds by returning the index.html.

After loading index.html and the Angular app/module, any requests that match its routing relative to its path will be handled by it -- you can find relevant information in this Angular reference, particularly focusing on html5mode

In this mode, Angular intercepts all links (following the "Html link rewriting" rules below) and updates the URL without performing a full page reload

Therefore, any request from your Angular app to /webapptest/page2 will align with its routing

.when('/page2', {
    templateUrl : 'resources/html/page2.html',

and will be exclusively handled by Angular, prompting it to request the corresponding templateUrl -- resources/html/page2.html.

At this stage, the URL will display /webapptest/page2, even though the server was not directly requested for that URL. If you refresh the page, the browser recognizes the history/location as /webapptest/page2 and attempts to retrieve it from the server, potentially leading to a 404 error if not found.


To resolve this issue, configure your server to enable Angular to manage all requests to /webapptest/**, essentially mapping all /webapptest/** routes to index.html.

You can implement a simple view controller

@Controller
public class SpaController {

  @RequestMapping(value={"/webapptest/**"}, method=RequestMethod.GET)
  public String app() {
    return "index"; 
  }
}

or include the above mapping in Spring's ViewControllerRegistry if already utilized.


By the way, is this check necessary?

if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}

Doesn't $location automatically switch to Hashbang mode for older browsers that do not support html5mode?

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

Here's a simple script to display a div or popup only once in the browser using plain vanilla JavaScript

// JavaScript Document I'm attempting to make a popup appear in the browser only once. I believe using local storage is the key, but all I can find are solutions involving jQuery. I really want to achieve this using plain JavaScript without relying ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Deactivate input fields within div elements that are not currently selected

Is it possible for me to disable input fields within a div based on a certain variable? Specifically, if the id of the div is not equal to 12, I would like to disable all input fields inside. Can someone assist with how to achieve this using jQuery? Much ...

Exploring the possibilities of combining mixitup with Vue.js 2.0 Component

Struggling to implement mixitup on vue.js; however, every time I check the mixitup target, it shows 0 elements in the container (mixer.getStatus().totalShow) Below is my complete vue.js component code: <template> <section class="main-co ...

Is it possible to generate a JSON file from a flowchart with the help of d3.js?

Situation: I'm currently in the process of developing a tool that will enable us to generate flow charts and then export the data into a JSON file for use in other services. Being new to JavaScript, I've come across d3 quite often. Can d3 handle ...

Exclude the file and directory patterns from being watched with PM2: ignore folder

I need help with configuring pm2 to stop monitoring folders that have names like cache or tmp. I've tried multiple approaches in my app.json configuration file: {"apps": [{ "name": "BSTAT", "script": &q ...

What steps can be followed to create functionality for having three pop-up boxes appear from just one?

I have implemented code that triggers pop-up boxes at the bottom of the screen when a user clicks on a name from a list displayed on the top right corner of the screen. <!doctype html> <html> <head> <title>Facebook Style Popu ...

Provide PDF files exclusively upon a successful submission of the form

What is the most efficient method for setting up a MEAN stack application to allow downloading a PDF attachment only after successful form submission? Please keep in mind that there is no user authentication in place. Anyone can access this form. Once the ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

What is the best way to create an HTML template with a table where the first column is divided into four cells and the second column only has one

Currently, I am working on a template using HTML and CSS. One issue that I am facing involves designing a table template with HTML and CSS. The specific problem occurs in the second row of the table where there are 4 cells in the first column and only one ...

What is the best way to cluster related data points and display them together?

In order to efficiently manage the data I receive, it is necessary to group it based on specific criteria and display these groups in the user interface. "ServiceRequest": [ {"Status": "Re-Open", },{ "Status": "Open", ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

Transforming Node's loops into asynchronous functions

I have the following sync function: for (var i = 0; i < results.length; i++) { var key1 = results[i]['__key']; for (var j = i + 1; j < results.length; j++) { ...

Database entries displayed using a CSS grid

Struggling to organize elements in a grid layout using CSS from my database. Despite all efforts, the items keep aligning to the left instead of forming a proper grid https://i.sstatic.net/5SfJZ.jpg I've attempted various methods to grid the items, b ...

Having trouble transmitting JSON data with Durandal JS and Knockout Binding

var newData = { a: ko.observable(), b: ko.observable(), c: ko.observable(), d: ko.observable() }; function setupControlEvents() { $("#save").on("click", handleSave); } function handleSave() { var dataToSen ...

Notify me when the AJAX requests are complete using jQuery upon completion

I am encountering difficulties with the callback function's functionality. My objective is to add 2 items to the cart by sending 2 asynchronous POST requests. Once these requests are both complete, I aim to update the partial view of the cart. However ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...