Organizing routes in Express.js and AngularJS

Having trouble setting up an express + angular app.

Successfully loaded the assets files into it.

Upon examining my code for Express and the html file, it seems that Express is only returning the index.html file, causing all routes to return that file.

Below is the code for Express:

//server.js

// set up ========================
var express = require('express'),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    path   = require('path'),
    app    = express(),
    mongoose = require('mongoose'),
    jwt    = require('jsonwebtoken'), // used for token operations
    config = require('./config'), // obtain config file
    User   = require('./model/users'), //mongo model
    routes = require('./middleware/routes'); 

// configuration =================
app.use(express.static('/client'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'});          
app.use(bodyParser.json());                                    
app.use(bodyParser.json({ type: 'application/json' }));
mongoose.connect(config.database);
app.set('superPin', config.secret);
// start server =================
//
app.listen(8080);
console.log('App started and is listening on port 8080');
//
app.get('/checkServer', function(request,response){
    response.send('Works fine. Server started at default get routing to check if server runs.');
});
//
app.get('*',function(request,response){
    response.sendFile(path.resolve('../client/view/index.html'));
});
//

and here is my index.html file:

<!DOCTYPE html>
<html>
  <head>
    <title>My Angular App</title>
  </head>
  <body ng-app="pmt">
    <div ng-view></div>
    <script src="client/assets/vendor/angular/angular.min.js"></script>
    <script src="client/assets/vendor/angular-bootstrap/ui-bootstrap.min.js"></script>
    <script src="client/assets/vendor/angular-message/angular-message.min.js"></script>
    <script src="client/assets/vendor/angular-touch/angular-touch.min.js"></script>
    <script src="client/assets/vendor/angular-ui-router/angular-ui-router.min.js"></script>
    <script src="client/assets/vendor/angular-touch/angular-touch.min.js"></script>
    <script src="client/assets/vendor/moment/min/moment.min.js"></script>
    <script src="client/controller/routes.js"></script>
  </body>
</html>

Attached is a print screen of my folder structure: https://i.sstatic.net/hfxvv.png

And here is the link to the repository: https://bitbucket.org/cojok/pmt/

Despite searching through related posts, I am unable to pinpoint what I may be doing wrong.

Encountering this error in the browser https://i.sstatic.net/pOmIK.png

Answer №1

It seems like your issue revolves around linking files in views and setting file routes on directories. Here is a solution for you:

app.use(express.static(path.join(__dirname, 'scripts')));
app.use(express.static(path.join(__dirname, 'Content')));
app.use(express.static(path.join(__dirname, 'Angular')));
app.use(express.static(path.join(__dirname, 'Views/Main')));
app.use(express.static(path.join(__dirname, 'Views/Authentication')));

Ensure that content, angular, and scripts are set as root directories and reference jQuery files accordingly:

<script src="angular-resource.js"></script> //Located in the angular folder at the root
<script src="angular-ui-router.js"></script> //Located in the script folder at the root
<script src="/Controllers/MainController.js"></script> //Located in the angular folder with child directories

Answer №2

I recently discovered my error, or perhaps it was just a quick fix. By making this adjustment:

 app.use('/client',express.static('../client/'));
 app.get('/',function(request,response){
    response.sendFile(path.resolve('../client/view/index.html'));
});

I was able to resolve the issue I was facing.

Thank you!

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 calling on-click function from a directive's template not being triggered

I am new to Angular and I'm experiencing an issue with my ng-click not working in certain contexts. Let me share my code and explain the problem more clearly. HTML : <div ng-app='myApp'> <section id="map-orders" ng-controller= ...

Tips for personalizing the webpack compilation process for transforming .vue files into .js files?

As a beginner in the realm of webpack plugins, I've grasped the idea behind the html-webpack-plugin, which empowers users to personalize the generation process of html files by webpack. In a similar vein, I am on the quest for a plugin tailored for . ...

The requested resource at / could not be found on the server

Currently, I am in the process of developing a webpage that utilizes Angular to dynamically alter DOM elements. The project includes a public folder housing HTML, CSS, JavaScript, and JSON files. To share the project, I have set up Node to run it from loca ...

How can I style the options and optgroups of a select dropdown with CSS, focusing on padding and margins?

In my experience, I have found that padding or margin CSS properties only seem to affect the appearance of options within the select menu in Firefox browser. I attempted the same styling in Internet Explorer and Chrome but it did not have any effect. Is ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

"Encountering an issue with Passportjs where the success callback is

I am currently working on enabling local authentication using passport js and sequelize in an express application. However, I am facing an issue where the success callback is not triggered upon successful authentication. Although the log indicates that the ...

React conditional statement within a map function embedded in a JSX element

Below is the function I have created to generate tabbed items: function ConstructTabs(props) { const tabs = props.tabs; const makeTabs = tabs.map((tab, index) => { <React.Fragment> <input className="input-tabs" id ...

PHP working with Ajax, receiving a status of 200 but still showing a readyState of 0

Snippet: function handleXMLHttpRequest() { var xhr; try { xhr = new XMLHttpRequest(); } catch (e) { try { alert("Error occurred"); xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ x ...

Revamp your website with an AJAX-powered login form that dynamically updates the page content upon successful

Imagine having a page with a dynamic login/logout feature in the header that operates smoothly via AJAX. When a user is not logged in, display a message saying "Hey, login" and provide the option to login via AJAX, which functions correctly. However, onc ...

Using the swiper carousel on WordPress results in an unexpected horizontal scrolling issue

Running an Elementor website, I need to incorporate various image carousels within my post content. Initially, I created a template for each carousel using Elementor. However, I have now decided to switch to utilizing a shortcode that leverages Elementor&a ...

How can we make it possible for the app to be sent to the background using a button within the application?

Can the app be minimized to the background using a button within the application? Some applications achieve this by minimizing when the exit option is pressed, rather than closing completely... I am looking to implement this feature in my Ionic app or th ...

blending javascript and php variables within ajax requests

I am working on a simple jQuery ajax feature, where I need to combine form data retrieved by JS with some PHP variables and send them all through ajax GET method. Here's what I have: var longform = $("input:text").serialize(); $.ajax({ url: & ...

Using the directive DEMO, create an ng-model specified for the `<input type="file"/>` element

I attempted to utilize ng-model on an input tag that has a type of file: <input type="file" ng-model="vm.uploadme" /> However, even after selecting a file, $scope.vm.uploadme remains undefined in the controller. What is the best way to retrieve th ...

Having trouble executing javascript with Ext.Ajax in Sencha-Touch2?

Currently, I am utilizing htmlPanel.js in Sencha-Touch as discussed in the Forum here to exhibit local HTML content. Even though I can load the HTML content with standard HTML tags, I'm facing issues with loading JavaScript. Here's the snippet o ...

I have chosen not to rely on Media Query for ensuring responsiveness in my Angular 2 application, and instead opted to utilize JavaScript. Do you think this approach is considered a

I am in the process of ensuring that my app is fully responsive across all screen sizes. Instead of relying on Media Query, I have chosen to use JavaScript with Angular 2 to achieve this responsiveness, utilizing features such as [style.width], *ngIf="is ...

How can I reposition an image diagonally to a specific location using JavaScript in p5.js? Is there a method to display an image and then conceal it at a chosen location in p5.js?

Is there a way to move the third image diagonally until it intersects with the two images? var pic1; var pic2; var pic3; let posX=0 let posY=0 const rightwall=350; function preload(){ pic1=loadImage("5.png") pic2=loadImage("iron.jpg&qu ...

Analyzing the similarities in properties between two arrays of objects in order to generate a pair of fresh arrays

I have two sets of data represented as arrays: var oldOrder = [{"Id": "10","Qty": 1}, {"Id": "3","Qty": 2}, {"Id": "9","Qty": 2}]; var newOrder = [{"Id": & ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

Why is it that the "await" keyword lacks the ability to truly await?

I created this code to access the google calendar API and retrieve information. To make it easier to understand, I added the variable x to the function. Initially, I expected x to be displayed as 1, however, it consistently shows up as 1. The main issue ...

What makes styling a success button in @material-ui so challenging?

I am currently utilizing the user interface framework found at https://material-ui.com/ My primary aim is to obtain a success Button and Chip. Can anyone provide insight on achieving this goal without resorting to less-than-ideal methods like those discus ...