我有两个不同的 react js 应用程序,我想根据 url 将用户重定向到应用程序
例子 :
app.get('/' , (req,res,next) => {
// redirect to first SPA
});
app.get('/admin' , (req,res,next) => {
// redirect to another SPA
});
如果要从 node.js 服务器提供 react 应用程序,只需发送每个应用程序的index.html
:
app.get('/admin', (req, res) => {
res.sendFile('admin_app/index.html');
});
app.get('/', (req, res) => {
res.sendFile('public_app/index.html');
});
如果这些文件是从同一台机器上的不同进程提供的,您将不得不代理请求:
const httpProxy = require('http-proxy');
const proxy = httpProxy.createServer({});
app.get('/admin', (req, res) => {
proxy.web(req, res, { target: 'http://localhost:3006/admin' });
});
app.get('/', (req, res) => {
proxy.web(req, res, { target: 'http://localhost:3006/' });
});
只要进程在127.0.0.1:3006
侦听所有公共地址,重定向也将起作用。但是重定向包括用户浏览器导航到不同的 URL。例如,如果您的 node.js 服务器运行在example.com
(即浏览器忽略的端口 80)并重定向到另一个进程,浏览器现在将显示example.com:3006
. 通过代理请求,URL 将保持在example.com
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句