我有2个快递服务器:
都可以使用以下方式在本地访问:
http://localhost:3000/news
http://localhost:3001/stock
我的目标:
从以下位置的代理服务器访问两个Express服务器端点 http://localhost:8008
我的问题:
我只能打第一个api1的端点
任何帮助将不胜感激 :)
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);
**编辑1:
我尝试了一下,它适用于api1端点,但不适用于api2端点。
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);
还在寻找解决方案!! @!请帮忙!
编辑2:工作解决方案
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);
编辑3(*奖金):在容器设置中应用解决方案-必须将localhost更改为容器名称(news和stock),代理才能正确使用容器。
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);
查询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);
查询http:// localhost:8008 / stock =>'来自api2的hello'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句