【发布时间】:2017-01-22 03:49:47
【问题描述】:
好的,我仍在尝试使用服务器端渲染构建 react.js 应用程序。我有很多时间处理带有参数的反应路由器。我无法从服务器端的路由中提取路由参数以对数据库进行正确查询。
这是我的 react-router 路由:
import {Router,Route} from "react-router";
import React from "react";
import App from "../components/app";
import {HomeContainer} from "../components/home";
import {TagContainer} from "../components/tag";
export function createRouter(hist) {
const routes = <Route component={App}>
<Route path="/" component={HomeContainer}/>
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
</Route>;
return (
<Router history={hist}>{routes}</Router>
);
}
在我向路由添加参数“:unique_name”之前,路由运行良好
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
在服务器端,我无法从路由中提取 unique_name 以在 DB 上进行查询:
这是服务器上的路由(使用 Node.js 和 Express.js):
const router = express.Router();
router.get("/tag/:unique_name", ServerRenderController.tagRender);
server.use(express.static(path.join(__dirname, '..', '/build')));
server.use(router);
这是我的“ServerRenderController.tagRender”:
function tagRender(req, res) {
console.log(req.params.unique_name);
/*
output :
mytag_unique_name -> this is the route params
style.css ->stylesheet - how the hell it become route params?
app.js -> client code - how the hell it become route params?
vendor.js -> vendor scripts - how the hell it become route params?
manifest.js -> manifest file -how the hell it become route params?
*/
match({browserHistory,routes, location:req.url}, (err, redirectLocation, renderProps)=> {
if (redirectLocation) {
//@TODO: response redirect location
console.log('redirect location');
}
if (err) {
//@TODO: response error
console.log(err.stack);
}
if (!renderProps) {
//@TODO: route to 404
console.log("no renderProps");
}
renderPage(renderProps); // return HTML to client with __PRELOADED_STATE__
}
问题:
- 我在服务器代码中做错了什么(路由,表达静态 中间件...)。
- 如何从路由中提取正确的路由参数? (当我浏览到http://localhost/tag/mytag_unique_name 时,我只想提取“mytag_unique_name”作为唯一的参数) 现在路由参数包括应该是的静态文件 作为 MIMETYPE css/js 发送。
【问题讨论】:
标签: express reactjs react-router