【问题标题】:react router server side rendering: How to get route params on server side?反应路由器服务器端渲染:如何在服务器端获取路由参数?
【发布时间】: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__
        }

问题:

  1. 我在服务器代码中做错了什么(路由,表达静态 中间件...)。
  2. 如何从路由中提取正确的路由参数? (当我浏览到http://localhost/tag/mytag_unique_name 时,我只想提取“mytag_unique_name”作为唯一的参数) 现在路由参数包括应该是的静态文件 作为 MIMETYPE css/js 发送。

【问题讨论】:

    标签: express reactjs react-router


    【解决方案1】:

    好的。原来我在引用样式表和脚本文件时犯了错误。 在服务端渲染代码一定要参考&lt;link href="/style.css" rel="stylesheet"/&gt;rel attr 的开头带有斜线 (/)。 请注意这里的任何人都有同样的问题。

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2018-02-05
      • 2015-04-19
      • 2017-11-11
      • 1970-01-01
      相关资源
      最近更新 更多