【问题标题】:How can I get react-router v4 defined params with express at server-side如何在服务器端使用 express 获取 react-router v4 定义的参数
【发布时间】:2018-10-19 02:03:27
【问题描述】:

我尝试从此网址获取:userId“albert” http://localhost:5000/search/albert?query=al&page=1 在服务器端但失败了,我该怎么做才能使用 express 在 node.js 上正确获取 react-router 定义的参数?

routes.js

[
  {
    path: '/search/:userId',
    component: Search,
  }, {
    path: '/search',
    component: Search,
  }
  ... 
]

server.js

server.get('*', async (req, res, next) => {
  const pageData = await routes
  .filter(route => matchPath(req.path, route))
  .map((route) => {
    console.log(route)
    return route.component
  })
}

【问题讨论】:

  • 你在使用 react-router-config 吗?
  • 不,我们不使用 react-router-config。如果我使用它,这个问题可以解决吗?

标签: node.js reactjs express react-router react-router-v4


【解决方案1】:

React-Router 方式

React Router V4 确实包含一种使用其matchPath() 函数在服务器端提取参数数据的方法,使用其标准parameter implementation"/path-name/:param" 路由匹配。

在这种情况下,它允许我在快速应用响应页面数据之前根据参数做很多服务器端的事情。

注意:这可能不是最基本的实现,但它是我使用matchPath() 的完整 SSR react 实现的精简版。

要求

  • 服务器端渲染的反应应用
  • React-router-dom v4
  • 集中路由文件(because SSR)
  • Express 应用服务器(我在 Firebase 上托管我的 express 应用)

在此示例中,服务器端快速应用程序尝试在新页面加载期间在每个组件中运行“initialAction”函数。它通过 promise resolve 和 reject 来知道函数何时完成运行,以及可能包含有用参数的请求对象,我们可以使用matchPath() 提取。它再次使用matchPath() 对每个匹配的路由执行此操作。

Routes.js 示例

:id 是 URL 中的“id”参数。

const routes = [
    {
        path: "/news-feed/:id",
        component: NewsFeed,
        exact: true
    },
]

export default routes;

组件示例

只显示组件中的initialAction()函数

import { Link, matchPath } from 'react-router-dom';

class NewsFeed extends Component {

    // Server always passes ability to resolve, reject in the initial action
    // for async data requirements. req object always passed from express to
    // the initial action.
    static initialAction(resolve, reject, req) {

        function getRouteData() {
            let matchingRoute = routes.find(route => {
                return matchPath(req.path, route);
            });
            console.log("Matching Route: ", matchingRoute);

            return matchPath(req.path, matchingRoute);
        }

        let routeData = getRouteData();
        console.log("Route Data: ", routeData);
    }

/** REST OF COMPONENT **/

Console.log 输出 为 url www.example.com/news-feed/test 将是

Route Data:  { path: '/news-feed/:id',
  url: '/news-feed/test',
  isExact: true,
  params: { id: 'test' } }

如您所见,我们在服务器端发现我们的参数没有使用正则表达式。 matchPath() 为我们完成了这项工作。我们可以使用漂亮、干净的 url。

服务器端 index.js

调用初始操作的位置,带有 promise resolve、reject 和 req 对象。 请记住,这是一个 firebase 托管示例,可能因不同的托管服务提供商而异 - 您的 initialAction 函数调用方法也可能不同

import React from "react";
import ReactDOMServer from 'react-dom/server';
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { StaticRouter, matchPath } from "react-router-dom";
import routes from "../shared/components/App/routes.js";
import express from "express";
import * as functions from "firebase-functions";

// Import Components, Reducers, Styles
import App from "../shared/components/App";
import reducers from "../shared/reducers";

// Prepare our store to be enhanced with middleware
const middleware = [thunk];
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

// Create store, compatible with REDUX_DEVTOOLS (chrome extension)
const store = createStoreWithMiddleware(reducers);

// Implement cors middleware to allow cross-origin
const cors = require('cors')({ origin: true });

const app = express();
app.get('**', (req, res) => {

    cors(req, res, () => {
        // Finds the component for the given route, runs the "initial action" on the component
        // The initialAction is a function on all server-side renderable components that must retrieve data before sending the http response
        // Initial action always requires (resolve, reject, req), and returns a promise.
        const promises = routes.reduce((acc, route) => {
            if (matchPath(req.url, route) && route.component && route.component.initialAction) {
                acc.push(new Promise(function (resolve, reject) {
                    // console.log("Calling initial action...");
                    store.dispatch(route.component.initialAction(resolve, reject, req));
                }));
            }
            return acc;
        }, []);

        // Send our response only once all promises (from all components included in the route) have resolved
        Promise.all(promises)
            .then(() => {
                const context = {};
                const html = ReactDOMServer.renderToString(
                    <Provider store={store}>
                        <StaticRouter location={req.url} context={context}>
                            <App />
                        </StaticRouter>
                    </Provider>
                );
                const preloadedState = store.getState();
                res.status(200).send(renderFullPage(html, preloadedState));

            })
            .catch(function (error) {
                console.log("Promise error at server", error);
            });
    });
});

module.exports = functions.https.onRequest(app);

【讨论】:

  • 您好 Mathew,我使用的方法与您的示例相同。当我点击 URL localhost:3000/news-feed/test 它不加载 NewsFeed 组件时,您能帮帮我吗.除了那些有参数的路线之外,所有其他路线都可以工作。你能帮忙吗?
【解决方案2】:

刚刚使用了一个示例 node.js 应用程序来制作一个 server.js,它可能类似于

const express = require('express')
const app = express()

app.get('/search/:userid', (req, res) => res.json({ key: `Hello World for search with id=${req.params.userid}` }))

app.get('/search', (req, res) => res.send('Hello World!i for search'))

app.get('*', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Example app listening on port 3000!'))

对于页码和其他 url 参数,您可以这样做

req.query['page'] 

检索参数。

【讨论】:

  • 感谢您的回复,我知道我们可以通过这种方式解决。只是想知道 react-router 是否提供 api 来实现此任务。
猜你喜欢
  • 2016-05-24
  • 1970-01-01
  • 2019-03-20
  • 2017-08-30
  • 2018-01-10
  • 2015-08-18
  • 2017-08-05
  • 1970-01-01
  • 2017-06-06
相关资源
最近更新 更多