What is the process for invoking a microservice (constructed in express js) from an angular application that is currently communicating with a sails js backend?

I had initially developed an application with Angular frontend and Sails JS backend. However, I recently separated some of the backend functions into a micro-service using Express. Now, I am looking for guidance on how to call these functions from my main application. Can anyone provide me with instructions on how to achieve this?

Answer №1

Here are a couple of methods to achieve this:

  1. CORS

    To ensure your microservice can freely communicate with the browser, you need to enable CORS. In Express, this can be accomplished as follows:

    const cors = require('cors');
    
    app.use(cors());
    

    If the endpoint requires credentials (e.g., login), additional options may need to be set for CORS:

     app.use(cors({
         credentials: true,
         origin: true,
         methods: 'POST,GET,PUT,OPTIONS,DELETE'
     }));
    

    For more details on configuring the cors middleware, refer to the documentation at: https://www.npmjs.com/package/cors

  2. Application Gateway

    An alternative approach is to run all your microservices behind a reverse proxy like Nginx, Apache2, or HAproxy. This method was commonly used by Amazon pre-2014 (before browsers supported CORS).

    Below is a basic example of an Nginx configuration for proxying your microservice:

    # The ^~ operator matches all urls that begin with the specified string:
    
    location ^~ /some/microservice {
      proxy_pass http://some.microservice.myapp.com;
    }
    

    An Application Gateway, as it's known in the industry, acts as a reverse proxy that maps multiple microservices to URL paths under a single domain name. Apart from enabling cross-origin requests, these gateways offer benefits like load balancing and firewall protection for internal servers.

Regardless of the approach you choose, fetching data from your microservices involves making AJAX requests using either traditional XMLHttpRequest or the modern fetch API:

// If CORS is properly configured on your server:
fetch('https://some.microservice.myapp.com/getdata')
  .then(function(response) {
    return response.json();
  })
  .then(function(result) {
    console.log(result);
  });

// When utilizing an application gateway:
fetch('https://myapp.com/some/microservice/getdata')
  .then(function(response) {
    return response.json();
  })
  .then(function(result) {
    console.log(result);
  });

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

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

I am unable to locate the module 'fs': I have exhausted all possible solutions to fix this problem

Attempting to delete a file from the local system using the unlink function, but encountering an error stating that it cannot find the module 'fs'. Below are some details on the relevant files: app.component.ts import * as fs from 'fs&apos ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

Disconnect a particular user using Passport.js

Whenever an administrator decides to block a user, I need to ensure that their active session is immediately disconnected. This will prevent them from accessing the application until their session naturally expires. The code snippet below outlines how this ...

Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code: router.get('/', (ctx, next) => { MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) { if (err) th ...

Node.js method convention - invoking self-defined functions

Consider a scenario where a Node module contains two functions, func1() and func2(). It is necessary for func1 to make a call to func2 during its execution. In order to test func2 independently, I have included both func1 and func2 in the exports by setti ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Executing NodeJS custom middleware to show parent function being called

Goal: Showcase the parent function of a middleware function shared = require('./RoutFuctions'); app.post('/link', shared.verifyToken, (req, res) => { ... } In the middleware function exports.verifyToken = functio ...

What to do when calling disabled() on a FormControlName causes all form fields to become invalid?

While working with a reactive form, I have observed that setting a formControlName to disabled() can cause the entire form to become invalid. Is there a way to ensure the form remains valid even after disabling a control? console.log('Before:' ...

Is there a way to automate the distribution of tasks to users in order to ensure that each user receives an equal number of assignments?

I'm in the process of developing an automated task manager that assigns tasks to users based on their role. Currently, I'm randomly selecting a user with the same role as the task from the list of users and assigning the task to them using math.r ...

Upgrade from Angular 7 to the latest version, Angular 8

Here is the content of my package.json file: "@agm/core": "^1.1.0", "@angular/animations": "^8.2.14", "@angular/cdk": "^6.4.7", "@angular/common": "^8.0.0", "@angular/compiler": "^8.2.14", "@angular/core": "^8.2.14", "@angular/forms": "^8.2.14", "@angular ...

The Slack-App-Watson feature seems to have trouble retaining the intent from the previous message it received

Currently, I am developing a Slack bot with the ability to retrieve weather information for a specified location. In the Watson conversation chat interface, Watson is performing well: me: Weather please Watson (detected #weather_asked): Where wou ...

error encountered: script not found during starting the application, leading to application crash when attempting to deploy on Heroku

I am a beginner in the world of coding, but I am eager to learn so that I can create a chatbot for my Facebook page. Below are the scripts I have inside each .js file and the errors I encountered. After running 'heroku open', the web displays an ...

Uh-oh! We encountered a little hiccup while running NodeJS on Azure with Sequelize for SQL

So I have been working on developing a NodeJs application on my Windows machine. Recently, I decided to deploy it on Azure cloud and set up a SQL Server instance. During the testing phase, where the node app was running locally and the SQL Server was conn ...

The node-inspector window appears void of any content

After installing node-inspector using npm install -g nodeinspector, I encountered an issue where the dashboard appears blank except for a search bar. I have attempted to start the app, inspector, and browser in different orders, as well as reinstalled nod ...

Struggling with optimizing assets in Jenkins pipeline causing Webpack build to get stuck

My Angular2 app uses webpack for both development and build purposes. While building my sources (webpack --profile --bail) on my local machine, the webpack process completes successfully. However, when running the same command in my Jenkins CI pipeline, t ...

Express not properly rendering static files

Jade template doctype html html head title= title meta(name='viewport', content='width=device-width, initial-scale=1.0') link(rel="stylesheet", href='/bootstrap/bootstrap.min.css') ...

Sequelize throwing Javascript heap out of memory error when inserting large files into database

I have successfully converted an excel file to MySQL on my local machine. However, when I try to do the same with larger files on a container limited to 2048MB of memory, it doesn't work. I attempted to increase the memory limit using node --max-old-s ...

Retrieve a formatted Word document from a C# endpoint to a Node.js server

I am currently facing an issue with my Node.js server that sends a GET request using axios to a C# endpoint with JSON as a parameter. The C# API then uses Newtonsoft.Json to deserialize the JSON, reads a Word file into memory, and inserts data. The final s ...

Running a series of scheduled tasks multiple times in a clustered Node.js environment

I have implemented a Node JS server cluster environment to maximize the usage of all cores on my server. However, I am facing an issue with a Cron Job that runs daily at 08:00 AM. Because of clustering, it runs multiple times (4 times since the server ha ...