好的,我还在尝试用服务器端渲染构建 react.js app。我有很多时间用 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>
);
}
路线运行正常,直到我向路线添加参数“:unique_name”
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
在服务器端,我无法从路由中提取 unique_name 来对 DB 进行查询:
这是 server(Using 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__
}
问题:
-
我在服务器代码中做错了什么(路由,表达静态 middleware...)。
-
如何从路线中提取正确的路线参数? (当我浏览到http://localhost/tag/mytag_unique_name时,我只想提取“mytag_unique_name”作为唯一的参数)现在路由参数包括应该作为 MIMETYPE css/js 发送的静态文件。
1 回答
好。结果我在对样式表和脚本文件的引用中犯了错误。在服务器渲染代码中必须使用斜杠引用
<link href="/style.css" rel="stylesheet"/>
(在rel
attr 的开头/)。注意这里任何人都有同样的问题。