What is the best way to combine two AngularJS apps on a single Express server?

I have scoured the internet to find solutions for my specific problem, but none seem to work quite right. I am attempting to serve two separate AngularJS apps based on incoming subdomains using express-subdomain with express. While the code seems to serve the correct app, it appears that none of the Angular modules are being included as I see many 'Uncaught SyntaxError: Unexpected token <' errors in the browser console which indicate that AngularJS was not loaded properly. Running just one AngularJS app works fine; the issue arises when I try to introduce sub-domain and serve a second static app.

I have already experimented with vhost but encountered similar issues.

server.js

app.use(subdomain('app1',express.static(__dirname + '/public/app1')));
app.use(subdomain('app2',express.static(__dirname + '/public/app2')));

require('./app/routes')(app); // configure our routes

app.listen(port);

routes.js

app.get('*', function(req, res) {
    var firstIndex = req.get('host').indexOf('.');
    var subdomain = req.get('host').substr(0,firstIndex).toLowerCase();
    if (subdomain === 'app1'){
      res.sendFile(root + '/public/app1/views/index.html');
    }else if (subdomain === 'app2'){
      res.sendFile(root + '/public/app2/views/index.html');
    }else{
      res.sendFile(root + '/public/app1/views/notfound.html');
    }
});

Answer ā„–1

if (subdomain === 'app1'){
      res.sendFile(root + '/public/app1/views/index.html');

This appears to be incorrect. Sending index.html in response to any request, even requests for js files, is not ideal. A better approach might look like this:

if (subdomain === 'app1' && req.url.indexOf('.') === -1){ 
} else if (subdomain === 'app2' && req.url.indexOf('.') === -1){
} else { /* return static asset */ }  
   ...

Answer ā„–2

To mimic different applications using a general JSON structure, create separate instances for each application and define all the necessary calls. Here's an example of how this can be achieved:

const routes = {
    routeApp1: {
        appTest1:{
            url: '/appTest1/appTest1',
            file: './mock/appTest1.json',
        },
        appTest2:{
            url: '/appTest1/appTest2',
            file: './mock/appTest2.json',
        },
    }

    routeApp2: {
        appTest1:{
            url: '/appTest2/appTest1',
            file: './mock/appTest1.json',
        },
        appTest2:{
            url: '/appTest2/appTest2',
            file: './mock/appTest2.json',
        },
    }
};

app.get(routes.routeApp1.appTest1.url, (req, res) => {
    res.send(JSON.stringify(require(routes.routeApp1.appTest1.file)));
});

app.get(routes.routeApp2.appTest2.url, (req, res) => {
    res.send(JSON.stringify(require(routes.routeApp2.appTest2.file)));
});

app.listen(3000, () => {
    console.log(`Mock server running on port ${port}!`);
});

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

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

Issue with socket malfunctioning when integrated with express

Iā€™m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...

Unable to retrieve link text following readFile function. Selector functions properly in Chrome console

My goal is to extract hyperlink text. Using the google chrome console with my selector, I am able to retrieve a list of 15 link texts as desired. However, when I execute my code with the same selector, the el.text returns undefined in console.log while th ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

Tips for troubleshooting Node.js mssql promise issues

Is there a way to pass the response data from one SQL Server stored procedure into another stored procedure for logging purposes? I've attempted different methods but encountered issues with connection pools and errors like HTTP Status: 500, subStatu ...

ExtJs encounters missing files in directory - Error: Module '<path>modern-app-3 ode_modules@senchaextpackage.json' not found

I am currently in the process of setting up a new ExtJs project by following the instructions provided here. Upon completing the installation of ext-gen, I proceeded to create a new app using the command ext-gen app -a -t moderndesktop -n ModernApp3, but ...

Having difficulty accessing the PDFKit generated document

I am having trouble generating and opening a PDF file in my NodeJs server. I used PDFKit to create the PDF file, following the code in the documentation: const doc = new PDFDocument({}); doc.text("Test"); const writeStream = fs.createWriteStream("MyTest.p ...

Display a comprehensive inventory of all bot commands within a designated category

When a user executes a command, I have various commands categorized and would like to present them accordingly. For instance, consider the following command: const Discord = require('discord.js') const { MessageEmbed } = require('discord.js& ...

Accessing parent directives for forms - custom form names and dynamic validation

Introduction My current task involves validating dynamically created forms within a directive. These forms are all managed and submitted separately. When the form is submitted, I need to display validation errors for each individual form without any issu ...

Scrolling the Ionic framework to a position below zero

My ion scroll is synchronized with another component for scrolling. I achieve this by using the function scroll1.scrollTo(left, top, false); Unfortunately, this function does not allow scrolling to a negative position, such as scroll1.scrollTo(left, -50, ...

Best practices for configuring Jade with Yeoman and Grunt for efficient templating

I am struggling with integrating layouts and partials effectively in my project. Can someone provide guidance on the correct setup? Currently, I am using grunt-contrib-jade. Here is my current file structure: app |_jade | |_layouts | | ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

What is the most effective way to search for multiple queries in MongoDB based on the key passed in the request parameter?

When a get request calls this API, the search key is dynamically passed in via the id parameter. We are specifically looking for objects that have the Later_Today_P property set to true. Example MongoDB schema: { "user_logged_email" : "<a href=" ...

Explain the concept of user roles using node_acl in combination with mongoose and express

I'm currently utilizing node_acl to handle authorization in my application. However, I'm unsure about how to implement roles for each user. app.js const mongoose = require('mongoose'); const app = express(); const security = require(. ...

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

Retrieve a collection of users along with their most recent two entries using TypeORM and SQL

What is the best approach to retrieve a list of users with their last two visited locations using SQL query? user-table id name xxx a xyx b zzz e visitedlocation-table id startDate userID location 1. 1/2/21 xxx USA 2. 1/3/21 ...

What steps should I take to fix the issue of "[ERR_REQUIRE_ESM]: Must use import to load ES Module" while working with D3.js version 7.0.0 and Next.js version 11.0.1?

Encountered a roadblock while integrating D3 with Next.js - facing an error when using D3.js v7.0.0 with Next.js v11.0.1: [ERR_REQUIRE_ESM]: Must use import to load ES Module Tried utilizing next-transpile-modules without success Managed to make D3.js ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Issue encountered while attempting to deploy Node.js on Azure Functions, stemming from the absence of the gRPC binary module

Although I have experience with Azure Functions using C#, this is my first time delving into Node.js within the realm of Azure Functions. Hence, I apologize in advance if this comes across as a beginner question or even an inappropriate one. I successful ...