Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my view disappears. Here is a snippet of relevant code:

Any assistance on this matter would be greatly appreciated. Thank you.

This is my file structure:

+-- client
|   app
|       admin.config.js
|       admin.js
|       admin.module.js
|   assets
|   views
|       admin
|           admin-edit.ejs
|           admin-list.ejs
|   lib
|       bower components
+-- server
|   routes
|       index.js
|       admins.js
|   models
|       Admin.js
|   config
|       dbconfig.js
|   server.js

In my Angular module.config I have:

function config($stateProvider, $urlRouterProvider, $locationProvider) {
    $stateProvider
        .state('admins', {
            url        : '/admins',
            templateUrl: '/views/admin/admin-list.ejs',
            controller : 'AdminController',
            resolve    : {
                loginRequired: loginRequired,
                getAdminList : getAdminList
            }
        });

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/admins');

My server.js file looks like:

/* Routes */
var routes = require('./routes/index');
var auth   = require('./routes/auth');
var users  = require('./routes/users');
var admins = require('./routes/admins');


var app = express();


/*************************************
 App initialization
 **************************************/

/* Auto increment mongoose plugin */
autoIncrement.initialize(connection);

/* Auth secret code*/
app.set('superSecret', dbconfig.SECRET);


/* View engine setup */
app.set('views', path.join(__dirname, '../client/views'));
app.set('view engine', 'ejs');


// uncomment after placing your favicon in /public

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static('client'));

app.use('/', routes);
app.use('/auth', auth);
app.use('/users', users);
app.use('/admins', admins);

My index route looks like:

var express = require('express');
var router  = express.Router();

/* GET home page. */
router.get('/', function (req, res) {
    res.render('index');
});


module.exports = router;

I tried adding this into my server.js

app.get('*', function (req, res){
        res.sendFile(path.join(__dirname + '/client/index.ejs'));
});

and in this case when I refresh page while my url is /admins I get downloaded index page.

I also tried adding in my index.js route

router.get('*', function (req, res) {
   res.render('index');
})

and as result of adding this is endless loop in my admins list.

In my index.ejs I have

<meta charset="utf-8">
<base href="/">

Answer №1

Wow, that's a lengthy piece of code. Check out this link. I shared this answer yesterday and I'm quite proud of it. It showcases an uncomplicated example of Angular routing in version 1.5. Don't forget to include the line

$locationProvider.html5Mode(true);
as I haven't incorporated it.

Answer №2

After spending some time searching for a solution, I finally came across the answer here. Instead of having specific pages, I decided to use an asterisk (*) for every get request in my authentication route:

router.route('/signup')

    /* Default rendering for index */
    .get(function (req, res) {
        res.render('index', {
            page: req.params.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

What are the steps to implementing a JavaScript WebWorker in a webpack environment?

Struggling to implement web workers in my web app and encountering difficulties. The addition of a new entry to the webpack.config.js file is not producing desired results. Attempting to utilize the npm package named worker-loader, however, facing challen ...

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

combine multiple keys into a single element with angular-translate

Within my application, I am retrieving translation keys from a single cell within a database table and dynamically displaying them on a settings page. While most entries will have just one key in the display object, there are some that contain multiple key ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

What is a method to omit elements within a nested child element from a selection without relying on the children() function

Here is an example of an element: <div id="foo"> <a href="#" class="some">click me</a> <div id="bar"> <a href="#" class="some">click me too</a> </div> </div> I am facing the challenge of selectin ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

Obtain the OAuth redirect code from the POST data on my Angular webpage

As a newcomer to AngularJS, I am facing an issue that has been persistent for hours despite my attempts to resolve it. Previously, I successfully developed a web application that connected with Google using OAuth 2.0 to retrieve Analytics data. However, af ...

Steps for enlarging the size of a content popover

I'm trying to figure out how to adjust the height of a content popover so that the footer appears below it. When I increase the height of the content, the footer stays in the same position. Shouldn't it move after the ion-content or at the bottom ...

Convert the information within the data variable into a well-formatted JSON structure

I am attempting to transmit JSON information to the server utilizing the following URL: . The data variable is being populated with valid JSON containing properties such as name, email, and URLs. ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Adding the AJAX response to an array within the AngularJS framework

I am currently working on a function that involves array objects. $http({ method: 'GET', url: 'select.php' }).then(function success(response) { alert(response); //$scope.posts=response.data; ...

Having trouble with prettyphoto functionality

Seeking assistance as I am struggling to get this working Here is how I have set it up: <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen"/ ...

Hiding Modal Box Upon User Login: A Step-by-Step Guide

After a user clicks the login button in my navigation, a modal box pops up. However, once the user logs in, the modal box does not disappear. How can I hide or remove the modal box when users click on the login button? This code snippet is from Home.vue: ...

I am working with Vue.js 2.0 and attempting to send an event from a `child component`

I've been working with Vue.js 2.0 and I'm facing an issue trying to emit an event from a child component to the parent component, but unfortunately, it's not functioning as expected. Here is a glimpse of my code: child component: <temp ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

Javascript addClass and removeClass functions are not functioning as expected

Can you help me figure out why the icon still goes into the "startSharing" section even when it is turned off? In my html file, I have the following code for the icon: <div class="startSharing"></div> And in my javascript file, I have the fo ...

I would like to add a border at the bottom of each item in a ul list

My current focus is on making my website responsive with a breakpoint set at 576px I am aiming to achieve the design shown in this image without any space in the border-bottom and have both elements expand to full width: menu li hover However, I'm c ...

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...