How one can copy/paste a route and get the 'right' page using React-router?

荒凉一梦 提交于 2019-12-11 18:21:51

问题


Routing is implemented on client and looks something like:

<Provider store={ store }>
        <Router history={ browserHistory }>
            <Route path="/" component={ Layout }>
                <IndexRoute component={ Tracking }></IndexRoute>
                <Route path="users" component={ UserTable }></Route>
                <Route path="user/:login" component={ UserPage }></Route></Route>
            </Route>
        </Router>
</Provider>

Server-side router looks something like:

app.get('/', checkAuthStatus, redirect.index);
app.get('*', redirect.UndefinedRoutes);

The problem is that when one copies a route (for example /user/32) and pastes it in different browser tab or just refreshes page /user/32, the client sends request to server which in its turn interprets it as a request to '*' and redirect wherever UndefinedRoutes redirects (usually to the main page). So, the question is, how to redirect to 'right route', which is in given case /user/32 ?


回答1:


Since you are not doing any serverside rendering, you don't need routing on the server. You only need to configure a fallback, for example like this:

import fallback from 'express-history-api-fallback';
import express from 'express';
import http from 'http';

// Set up express
const app = express();
const server = http.createServer(app);
const root = `${__dirname}`;

// History Fallback for express
app.use(express.static(root));
app.use(fallback('index.html', { root }));

// Listen
server.listen(8080, '0.0.0.0');


来源:https://stackoverflow.com/questions/39980072/how-one-can-copy-paste-a-route-and-get-the-right-page-using-react-router

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