I have 2 express servers:
Both are accessed locally using:
http://localhost:3000/news
http://localhost:3001/stock
My aim:
Access both express servers endpoints from a Proxy server on http://localhost:8008
My Issue:
I can only hit the first api1's endpoints
Any help would be greatly appreciated :)
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const api1 = createProxyMiddleware({
target: 'http://localhost:3000'
});
const api2 = createProxyMiddleware({
target: 'http://localhost:3001'
});
const app = express();
app.use(api1);
app.use(api2);
app.listen(8008);
**edit1:
I tried this out, which works for api1 endpoints but not api2 endpoints.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware('/', {
target: 'http://localhost:3000'
});
const apiProxytwo = createProxyMiddleware('/', {
target: 'http://localhost:3001'
});
const app = express();
app.use(apiProxy,apiProxytwo);
app.listen(8008);
Still looking for a solution!!@! Help please!
Edit 2: Working solution
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/news/*', createProxyMiddleware({ target: 'http://localhost:3000', changeOrigin: true ,}));
app.use('/stock/', createProxyMiddleware({ target: 'http://localhost:3001', changeOrigin: true, }));
app.listen(8008);
Edit 3(*bonus): Applying solution in container setup - have to change localhost to container names(news and stock) for proxy to work with containers correctly.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/news/*', createProxyMiddleware({ target: 'http://news:3000', changeOrigin: true ,}));
app.use('/stock/', createProxyMiddleware({ target: 'http://stock:3001', changeOrigin: true, }));
app.listen(8008);
proxy.js:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/news/*', createProxyMiddleware({ target: 'http://localhost:3000', changeOrigin: true }));
app.use('/stock', createProxyMiddleware({ target: 'http://localhost:3001', changeOrigin: true }));
app.listen(8008);
newsServer.js
const express = require('express');
const app = express();
app.get('/news/headlines', (req, res) => {
res.send('hello from headlines')
});
app.get('/news/other', (req, res) => {
res.send('hello from other')
})
app.listen(3000);
query http://localhost:8008/news/headlines => 'hello from headlines'
stockServer.js
const express = require('express');
const app = express();
app.get('/stock', function(req, res) {
res.send('hello from api2');
});
app.listen(3001);
query http://localhost:8008/stock => 'hello from api2'