首页 > 解决方案 > StaticRouter 不适用于服务器渲染中的动态路由

问题描述

我在路线中有一个动态参数。当我直接打开 URL 时,它会引发错误。

为了让我的服务器知道我在服务器渲染中使用静态路由器的路由。

这是我的服务器渲染代码:

const serverRender = (req, res) => {
  const routes = [
    {
        path: '/',
        exact: true,
        component: Signin
    }
    {
        path: '/shared/:id',
        component: Shared,
        fetchInitialData: path => sharedInitialData(path)
    }
  ];

    const activeRoute = routes.find(route => matchPath(req.url, route)) || {}

    const promise = activeRoute.fetchInitialData ? activeRoute.fetchInitialData(req.path) : Promise.resolve()

    const theme = createMuiTheme({
        palette: {
            primary: blue
        },
        typography: {
            useNextVariants: true
        }
    });

    const sheets = new ServerStyleSheets();

    promise.then(data => {
        const app = renderToString(
            sheets.collect(
                <ThemeProvider theme={theme}> 
                    <Provider store={store}>
                        <StaticRouter location={req.url} context={{data}}>
                            <App />
                        </StaticRouter>
                    </Provider>
                </ThemeProvider>
            )
        )

        const css = sheets.toString();
        res.send(renderFullPage(app, css))
    })
    .catch(error => console.log(error));
}


const renderFullPage = (html, css) => `
    <!DOCTYPE html>
    <html>
        <head>
            <style>
                a{
                    text-decoration: none;
                    color: #000
                }
                ${css}
            </style>
        </head>
        <body>

            <div id="root">${html}</div>

            <script src="main.js"></script>

        </body>
    </html>
`


async function sharedInitialData(path) {
  const id = path.split('/').pop();
  return id;


}

当我打开 /shared/12345 时,我在控制台中收到错误消息。 Uncaught SyntaxError: Unexpected token < main.js:1

main.js 是我的 webpack 生成的 bundle 文件

我的捆绑文件填充了 HTML 而不是 js。我认为这是问题所在

标签: node.jsreactjsreact-routerisomorphic-javascriptserver-rendering

解决方案


我认为问题在于<script>您在renderFullPage(). 我认为您main.js的无法访问。您可以尝试在路径中添加斜杠(/)吗?

尝试更改<script src="main.js"></script><script src="/main.js"></script>


推荐阅读