我在路线中有一个动态参数。当我直接打开 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。我认为这是问题所在