我的应用程序中有这个路由器:
<Router history={ browserHistory } >
<Route path="/" component={Header}>
<IndexRoute component={Main} />
<Route path="view" component={ViewItem} />
</Route>
</Router>
每当我尝试渲染/ view时,它会将indexroute渲染一瞬间,然后完全渲染/ view。注意:我正在使用react-router的服务器端渲染。
由于
编辑:
服务器端代码:
router.get('/', function (req, res) {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
// You can also check renderProps.components or renderProps.routes for
// your "not found" component or route respectively, and send a 404 as
// below, if you're using a catch-all route.
const store = createStore(reducers);
const html = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
const initialState = store.getState();
res.status(200).send(renderFullPage(html, initialState));
} else {
res.status(404).send('Not found')
}
})
});
function renderFullPage(html, initialState) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
<link rel="stylesheet" href="stylesheets/main.css">
</head>
<body>
<div id="reactbody"><div>${html}</div></div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
<script src="../bin/app.bundle.js"></script>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
</body>
</html>
`
}
答案 0 :(得分:0)
您的路线仅在'/'上匹配,而不是'*'。这应该是router.get('*', function (req, res) {
。由于这将是一个“全部捕获”路线,它必须在每个其他路线之后。
但是......如果这是你唯一的路线,那么试图获得/view
我会认为会返回'找不到/查看',所以必须有其他东西来处理它。
在旁注中,您可能不希望在每个网络请求上创建存储,您可以将该行移到router.get
之外。
答案 1 :(得分:0)
修好它。我必须使用req.originalUrl,因为req.url总是返回“/”。我刚刚搜索了Express 4.x api,显然req.url甚至不再存在。
希望将来对某人有所帮助。