如何在同一服务器上使用节点js重定向以响应js应用程序? [英] how to redirect to react js application using node js, in same server?

查看:46
本文介绍了如何在同一服务器上使用节点js重定向以响应js应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的react js Application,我想根据URL将用户重定向到该应用程序

I have two different react js Application, and i want to redirect the user to the application depending on the 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 :

If the react app is to be served from the node.js server, simply send each app's index.html:

app.get('/admin', (req, res) => {
  res.sendFile('admin_app/index.html');
});

app.get('/', (req, res) => {
  res.sendFile('public_app/index.html');
});

如果这些文件是从同一台计算机上的不同进程提供的,则必须代理请求:

If those files are served from a different process on the same machine you will have to proxy the requests:

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 上.

Redirects would also work, as long as the process at 127.0.0.1:3006 listens on all public addresses. But a redirect includes that the users browser navigates to a different URL. E.g. if your node.js server was running at example.com (i.e. port 80, which the browser omits) and redirects to the other process, the browser would now show example.com:3006. By proxying the request, the URL will stay on example.com.

这篇关于如何在同一服务器上使用节点js重定向以响应js应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆