how to redirect to react js application using node js, in same server?

别来无恙 提交于 2021-01-07 02:32:40

问题


I have two different react js Application, and i want to redirect the user to the application depending on the url

example :

app.get('/' , (req,res,next) => {
  // redirect to first SPA
});

app.get('/admin' , (req,res,next) => {
  // redirect to another SPA
});

回答1:


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/' });
});

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.




回答2:


How about in a route middleware, res.redirect('http://someOtherServer/?

Such as res.redirect('http://localhost:5000').

Maybe this other answer will help Nodejs - Redirect url



来源:https://stackoverflow.com/questions/51467096/how-to-redirect-to-react-js-application-using-node-js-in-same-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!