你可以使用反应服务器将你的请求转发到后端吗?

can you use react server to forward your request to backend?

我正在开发一个工具,前端是用 React js 制作的(create-react-app 并用 serve 提供服务),后端是用 express+node 制作的,两个服务器都是 运行 在远程机器上的不同 Docker 容器上。现在的问题是系统管理员说他只会让外部可以访问前端,而后端容器只能由前端容器访问。由于我在 /API/example 上调用 XMLHttpRequest 并且后端没有 public URL 所以我可以使用前端服务器将我的请求重定向到后端吗?

为了让我自己清楚这就是我想做的,前端是 https://frontend.com 上的 运行,我从浏览器 API/example 调用 https://frontend.com/API/example 和服务器会将此调用重定向到后端并回复响应。

您应该使用某种网络服务器而不是 serve npm package. The problem in your case is that you want to proxy all requests to backend and serve package is only a static server. The easiest method for you is to write a custom node js script, serve the static assets (e.g. with express) and proxy all requests to backend. (e.g. with express-http-proxy)。

示例代码如下所示:

const proxy = require('express-http-proxy');
const app = require('express')();  
app.use('/api', proxy('http://backend.url')); // this will proxy all incoming requests to /api route to backend base url
app.use(express.static(‘path/to/your/static/assets’)); // these were previously served with serve
app.listen(3000, () => console.log(‘Frontend listening on port: 3000’));

另一种可能的方法是使用 nginx、apache 或任何您喜欢的网络服务器,并做基本相同的事情。