gpt4 book ai didi

node.js - 如何在同一服务器中使用 Node js重定向到react js应用程序?

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:43 24 4
gpt4 key购买 nike

我有两个不同的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 上的进程监听所有公共(public)地址,重定向也可以工作。但重定向包括用户浏览器导航到不同的 URL。例如。如果您的 Node.js 服务器运行在 example.com(即端口 80,浏览器省略)并重定向到其他进程,则浏览器现在将显示 example.com:3006。通过代理请求,URL 将保留在 example.com 上。

关于node.js - 如何在同一服务器中使用 Node js重定向到react js应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51467096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com