Setting up proxy middleware in an express application

My application is structured with a frontend server (React) serving static files and a backend server (Express). I have noticed that custom header requests trigger preflight requests, causing latency in my application. My goal is to eliminate these preflight requests for improved performance.

Let's consider this scenario:

frontend: example.web.com

backend: example.api.com

One solution I came across is setting up proxy middleware in the backend server to route requests internally, avoiding the need for requests to bounce from frontend to backend directly.

const proxy = require('http-proxy-middleware');
const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors({
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    allowedHeaders: "authorization"
}));
let options = {
    target: 'http://localhost:5001/',
    changeOrigin: true,
    logLevel: 'debug',
    onError: function onError(err, req, res) {
        console.log('Something went wrong with the proxy middleware.', err);
        res.end();
    }
};
app.use("/", proxy(options), indexRouter);

I was hoping to bypass preflight requests when sending non-"simple" requests. While I knew that using proxy middleware could help achieve this, I needed guidance on how to properly configure it within my Express application.

Answer №1

The http-proxy-middleware is designed to forward responses obtained from the target API server. It does not proceed to the next middleware in line.

Using app.use("/", proxy(options)) will direct all incoming requests on your server to the specified target API. For example, a request to yourserver.com/items will be redirected to targetapi.com/items. To accommodate custom routes, either apply a prefix to the middleware (app.use("/api", proxy(options))) or ensure that other middlewares are mounted prior to the proxy.

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 is the best way to eliminate the "0"s from the center of items within an array?

I have developed a table sorter that handles columns containing both letters and numbers, such as "thing 027". To facilitate sorting, I prepended zeros to the numbers. However, I am now looking for a cleaner way to remove these zeros from the numbers using ...

Moving a Ball Back and Forth Using Three.js

I’m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence. var geometry = new THREE.SphereGeometry( 5, 32, 32); var material = new THREE.MeshPhongMateri ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Retrieve data from a form on the server side using an Ajax request

I am currently working on submitting form data through an Ajax call. Here is the relevant form code: <form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST> <div class="form-group"> <labe ...

Unable to navigate through bootstrap dropdown items using keyboard shortcuts

I am currently working on a bootstrap dropdown menu that is filled with time zone details. Everything seems to be in order as the dropdown gets populated correctly. However, when I click on it and try to select an item by pressing a key on the keyboard (fo ...

Is there a way to change the name within an array of objects?

let myArray = [ { age: 21 }, { name: 'Sara' }, { test01: 'bla' }, { test02: 'bla' } ]; I have an array of objects and I need to update only the "name" property. How should I go about it? This is the desired outcome: ...

Angular 10 does not reflect changes in the array when they occur

My component receives an array of offers from an Observable. However, when the list is modified (a offer is deleted), the component's list does not update accordingly. I attempted to use ngOnChanges to resubscribe to the list and update it in my comp ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

Electron employee: Concealed BrowserWindow leads to delay in the interface

My worker runs in a hidden browser window and sends multiple requests simultaneously. However, these requests from the worker end up causing lag and freezes in the main browser window. Any suggestions for resolving this issue? ...

variables for expressjs views

Having some trouble with this code snippet and it seems like there's a simpler solution. The error message I'm getting is: /* * GET home page. */ exports.index = function(req, res){ exec('ls -l ~/Sites/branches | grep "^d"', fun ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Users are experiencing inconsistent data population issues with Node.js Superagent

In my code, I have a route that sends a request to an API using super agent to retrieve project information. The request includes headers set with .set and the response should be stored in the project_results variable. However, there's a peculiar iss ...

How can we achieve the same result as express' res.sendStatus(200) in Next.js api serverless functions?

I used to use the following code in some of my express routes. return res.sendStatus(200); However, the res object from NextApiHandlerType does not support that method. In this case, what would be the equivalent? import { NextApiHandler } from "next ...

Transform an array of object's designated key values into a string that is separated by commas

Is there a way to convert specific key values of an object into a comma-separated string? I have been able to do this with arrays, but my current challenge is that my data is an array of objects. I want to convert each 'id' value into an array of ...

Modifying JavaScript using JavaScript

I'm looking for a solution to change the URL of a button in sync with the iframe displayed on the screen using JavaScript. The challenge I'm facing is figuring out how to dynamically update the button's URL based on the iframe content. Here ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

Display a collection of objects using Jade / Pug syntax

Struggling to find resources on Pug / Jade templating, turning to this platform for help. I've been diving into documentation on iterations along with consulting this helpful link. Working with Node.js, Express, and pug for a school project - a mock ...

Adjust the node's location in Cytoscape.js

I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...