SoFunction
Updated on 2025-03-10

How to use express to proxy services

Both nodejs and nginx can be reverse proxyed to solve cross-domain problems.

Local Service

const express = require('express')
const app = express()

//If it is in the front, the rear/start will be intercepted('/', (req, res) => ('Hello World!'))

(('public'));// Static resources('/dist', ((__dirname, 'public')));// Static resources
//404
('/test', function (req, res, next) {
  (404).send("Sorry can't find that!");
});

(function (req, res, next) {
  //TODO middleware, each request will pass through  next();
});

(function (err, req, res, next) {
  //TODO failed middleware, and after the request error, it will pass  ();
  (500).send('Something broke!');
  next();
});

(4000, () => ('Example app listening on port 4000!'))

Use with request

This will proxy the requests from other servers

const request = require('request');
('/base/', function (req, res) {
  let url = 'http://localhost:3000/base' + ;
  (request(url)).pipe(res);
});

Using http-proxy-middleware

const http_proxy = require('http-proxy-middleware');
const proxy = {
 '/tarsier-dcv/': {
  target: 'http://192.168.1.190:1661'
 },
 '/base/': {
  target: 'http://localhost:8088',
  pathRewrite: {'^/base': '/debug/base'}
 }
};

for (let key in proxy) {
 (key, http_proxy(proxy[key]));
}

Listen to local file changes

Use the nodemon plugin.

--watch testIt refers to listening to all files in the test folder in the root directory, and the service will be restarted if there is any change.

"scripts": {
 "server": "nodemon --watch build --watch test src/"
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.