好的,我还在尝试使用服务器端渲染构建react.js应用。我有很大的时间处理带有参数的react-router。我无法从服务器端的路由中提取路由参数来对DB进行正确的查询。
这是我的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>
);
}
路由运行正常,直到我添加参数&#34;:unique_name&#34;到路线
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
在服务器端,我无法从路由中提取unique_name以在DB上进行查询:
这是服务器上的路由(使用Node.js&amp; Express.js):
const router = express.Router();
router.get("/tag/:unique_name", ServerRenderController.tagRender);
server.use(express.static(path.join(__dirname, '..', '/build')));
server.use(router);
这是我的&#34; ServerRenderController.tagRender&#34;:
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__
}
问题:
答案 0 :(得分:0)
行。结果我在对样式表和脚本文件的引用中犯了错误。
在服务器渲染代码中必须引用<link href="/style.css" rel="stylesheet"/>
在rel
attr的开头用斜杠(/)表示。
注意这里任何人都有同样的问题。