'How to integrate a proxy program in nodejs and redirect localhost:5000/api to localhost:5001 [closed]

In my project, a nodejs and asp.net core webapi exist together. the clientApp use http://localhost:5000 to access, and the asp.net core webapi backend use http://localhost:5001 to access. When there is a backend request http://localhost:5000/api, we want to redict it to http://localhost:5001 directly.

From Phil and Ninezero90hy suggestion, I have used http-proxy-middleware to setup a proxy js, and use command node to execute it seperatly. It works fine.

proxy.js

//proxy setup by using express framework
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
app.use(
    '/api',
    createProxyMiddleware({
        target: 'http://localhost:5001',
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
            '^/api': 'http://localhost:5001/api',
        },
    }),
);
app.listen(5000);

I want to integrate this program into my project, I found I can't do it directly. When I startup the web project, the command 'npm run dev' is executed, and it is different with node command enviorement. How can I make the proxy program into it. Could someone make any suggestion here. Thanks!



Solution 1:[1]

For example

{
  ...
  "devDependencies": {
    ...
    "http-proxy-middleware": "^2.0.4"
    ...
  }
  ...
}

or

npm install -D http-proxy-middleware

or

yarn add http-proxy-middleware --dev

? These three methods produce the same results.

Add the SetupProxy.js file to the src child.

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    '/api/boards',
    createProxyMiddleware({
      target: 'http://localhost:5001',
      changeOrigin: true,
      logLevel: 'debug',
      pathRewrite: {
        '^/api/boards': 'http://localhost:5001/api/boards',
      },
    }),
  );
};

/api/boards is api url example.
You can decide to change the api url.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1