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

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

Converting Dates with Ractive.js

Is there a way to transform the Epoch time value retrieved from a JSON endpoint into a readable time string format such as "Tue 19 Jan 11:14:07 SGT 2038" without relying on external libraries like moment.js? var ractive = new Ractive({ el: '#cont ...

Retrieve SQL data and store it in a JavaScript variable

Need assistance with fetching data from SQL and storing it in a JavaScript variable. I have already connected PHPMyAdmin to my website. I am attempting to retrieve two variables (date) from my SQL table. JAVASCRIPT: var countdown_48 = new Date; countdow ...

Creating an array of options for a jQuery plugin by parsing and populating

I am currently in the process of developing my very first jQuery plugin. The main function of this plugin involves taking JSON data and loading it into a table. Although most of the logic has been implemented successfully, I am facing challenges when it co ...

Revise the form used to edit data stored in Vuex and accessed through computed properties

My form component is used for client registration and editing purposes. Upon creation of the form component, I check if there is an ID in the URL to determine which type of form to display. If no ID is present (indicating a new client registration), all fi ...

Occasionally, the 'req.user' property in Passport may unexpectedly become undefined

Currently, I am utilizing Passport for authorization and storing sessions in MongoDB using the 'connect-mongo-session' module. One issue I have encountered is that sometimes, when attempting to log in after some time has passed, the req.user obje ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

When utilizing the .populate() method in Mongoose, how can you retrieve and append ObjectIds with extra attributes to an array (which is returned by .populate()) collected from the

When using the .populate() method in Mongoose, how can I retrieve and add ObjectIds with additional properties to an array (returned by .populate()) if their corresponding document in the collection no longer exists? This question pertains to MongoDB and ...

Unable to store acquired data into a list upon retrieval with Mongoose

I am utilizing express.js and mongoose to retrieve data from a collection, store it in a list, and then send it to an ejs file. However, I'm facing an issue where the data is not being stored in the list. Here's my code: app.get("/", (req, res) ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

Node.js unable to serve static files due to path issue (unable to access directory "/../")

Seeking Help with Serving CSS Files in Express In my routes.js file, I am trying to figure out how to serve all the files located inside the css folder as static files. Can anyone assist me with this? Screenshot of path structure (Please edit and display ...

Trouble with clicking buttons in Java and Selenium web scraping

Hey everyone, Currently, I'm working on a Java Selenium script that automates clicking and filling forms for me. I've written a line of code that's causing me some trouble. The intention is to click on a button, but it's not happening ...

unable to access POST information

I have encountered an issue with getting a basic AJAX POST to function properly. After facing difficulties with using a jQuery .click, I switched to an onclick method. I am unsure if I am making a glaring mistake or if there could be an issue with Apache s ...

Integrating TypeScript into an established create-react-app project

Struggling to integrate TypeScript into an existing create-react-app? I've always added it at the beginning of a project using create-react-app my-app --scripts-version=react-scripts-ts, but that's not working this time. The only "solution" I co ...

JavaScript - Sort an array containing mixed data types into separate arrays based on data

If I have an array such as a=[1,3,4,{roll:3},7,8,{roll:2},9], how can I split it into two arrays with the following elements: b=[1,3,4,7,8,9] c=[{roll:3},{roll:2}]. What is the best way to separate the contents of the array? ...

JAX-RS backend powering an Angular frontend

My Java backend uses Jersey, a JAX-RS implementation, running on a Glassfish server on port 8084. I have also created HTML5/JS/AJAX pages to display the data and confirm that the REST implementation is functioning properly. Now, I am working on developing ...