How to Eliminate the Hashtag from the URL in AngularJS Version 1.x

I'm currently in the process of creating a web application using Angular 1.x (not Ionic, just a regular website). My goal is to eliminate the '#' from the URLs. I've already set html5mode to true and added a base tag within the head section of my index.html file. Everything works smoothly until I refresh the pages. In html5mode, the URL is mistaken for a server request when refreshing. I am working locally with gruntjs via the grunt-contrib-connect plugin, and hosting the website on GoDaddy's Linux Hosting Server. I want to configure html5mode (remove hash from URLs) in both the development and production environments. Note: I am also using ui.router with states in this scenario.

Answer №1

By default, AngularJS uses hash(#) in the URLs for routing.

For instance:

http://example.com/
http://example.com/#/about
http://example.com/#/contact

To eliminate the hashtag from the URL, two steps are required:

  • Setting up $locationProvider
  • Configuring the base for relative links

Utilizing $location Service

In AngularJS, the $location service decodes the URL in the address bar and manages changes to the application accordingly.

Implementing $locationProvider and html5Mode

The $locationProvider module will be used along with setting html5Mode to true.

This process occurs during Angular application definition and route configuration.

angular.module('stackoverflow', [])

.config(function($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl : 'partials/home.html',
            controller : homeController
        })
        .when('/about', {
            templateUrl : 'partials/about.html',
            controller : aboutController
        })
        .when('/contact', {
            templateUrl : 'partials/contact.html',
            controller : partialController
        });

    // utilize the HTML5 History API
    $locationProvider.html5Mode(true);
});

Establishing Relative Links

To navigate within the application using relative links, it is essential to include a <base> element in the <head> section of your document.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">

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

There exist various methods for configuring this setup, and having the HTML5 mode enabled will automatically resolve relative links.

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

The argument type 'bool' in EAzureBlobStorageFile is unrecognized, along with the exception '*** -[__NSArrayM objectAtIndexedSubscript:]'

Encountered some issues... An error occurred with an unknown argument '_Bool' in the method -[EAzureBlobStorageFile configure:key:container:token:]. It seems that RCTConvert needs to be extended to support this type. Also, there was an exceptio ...

Form Automatically Submits Data Upon Loading of Page

I am currently facing an issue with my hidden div that is being loaded when I click the submit button. The form is sending results upon page load, and even though I have included the validateForm() function and called it at the end of the submit function ...

Tips for replicating input fields that fetch information via ajax requests

My current code fetches data using AJAX from the database and allows for adding an unlimited number of text fields: <div class="input" id="itemRows"> <div class="clone"> <style> .txtHint { width:95 ...

How to correctly position an object upright on a wall in Three.js WebXR(AR) and rotate it effectively

I'm currently facing a challenge trying to position an object vertically on a wall with the correct rotation. For illustration purposes, I've replaced the object with a reticle in the images provided. As shown in the last two pictures, the reticl ...

How can I retrieve the text input from a physical barcode scanner in a React Native screen?

Currently, I am developing a mobile application with React Native version 0.68.2. I am seeking a solution to detect barcode scanning events from a physical scanner hardware that is integrated into the mobile device as a handheld scanner. The key requirem ...

How to manage ajax URLs across multiple pages?

I have my website set up at http://example.com/foo/ within a directory, separate from the main domain. Through the use of .htaccess, I've configured the URLs to appear as http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com ...

Dealing with delays in Protractor

After spending a considerable amount of time developing automated tests in Protractor, I have encountered situations where the only solution seems to be using the browser.sleep() function. While it is not my preferred method, sometimes it becomes necessary ...

Experiencing issues with recognizing HTML DOM functions during Jest testing

I encountered an issue that reads as follows: TypeError: document.querySelector is not a function This error occurred in the line below: selectElement = document.querySelector('#selectbox'); The purpose of this line is to retrieve the selec ...

When cycling through an array in ReactJS, HTML tags are not displayed or processed

I'm diving into the world of ReactJS and trying to grasp the fundamental concepts. To pros out there, my question might seem like a beginner's query ;) Here's the component I am working on: import React from "react"; function Nam ...

Issue with inconsistent error handling in Mui DateTimePicker and react-hook-form

I am currently facing an issue with a DateTimePicker component that I am trying to integrate into a form controlled by react-hook-form. The validation is straightforward - I am using the disablePast prop on the DateTimePicker to ensure that the selected da ...

Guide on removing the complete document in MongoDB with Node.js by utilizing the ObjectId

The objectID I'm working with is idd=60041d4312e61330c4b93b9b, and I tried using the following code: db.collection('users').remove({"_id":"ObjectId("+idd+")"}) Unfortunately, this approach isn't achieving the desired result. ...

Angular appears to be experiencing technical difficulties

Exploring Angular as a beginner, I am working with a local REST API (Express app) and Angular code in the public folder. Currently, everything is functioning smoothly - I can add, update, and delete items in a locally running Mongo db. Check out the code h ...

Arranging the index of an array according to a separate array of objects in JavaScript using Vue

I have two arrays of objects that need to be sorted based on the value of a key in the other array. array1: [ { group: 'GROUP1', sort_order: 1, }, { group ...

Unable to successfully call a directive function from a nested child directive

I'm facing a challenge with utilizing a directive that was created by another developer to notify my directive when the ngRepeat inside of it has completed its creation. My parent directive has an isolate scope and includes a function within its scop ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

Sending the dot character as a parameter in AngularJS $http requests

I am attempting to pass the character . (dot) as a string in my Nodejs API call. I am utilizing the AngularJS $http object. Upon inspecting, I can confirm that the API call is indeed being made with the dot (.) character that I inputted in the search box. ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

React: troubleshooting error of empty object displayed by console log

Just diving into the world of React and facing a challenge with importing a list of objects from a JS file to set them as the initial state of my app. Here's what I've tried: import allSamples from './reducers/reducerSamples'; var App ...

What is the best way to horizontally center a div with the layout attribute set to "row"?

I am currently working with a grid composed of cards from the Angular Material library. The issue I am facing is that the cards have a fixed size, which results in extra space on the right immediately after wrapping. My goal is to eliminate this space by ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...