我在路由中具有动态参数。当我直接打开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;
}
当我打开/共享/12345时,我会在控制台中获得错误。 uckulting Syntaxerror:意外的令牌&lt;main.js:1
main.js是由WebPack生成的我的捆绑文件
我的捆绑文件用HTML而不是JS填充。我认为这是问题
我认为问题在于您在renderFullPage()
中给出的<script>
中的路径。我认为您的main.js
无法访问。您可以尝试在路径中添加斜线(/(吗?
尝试将<script src="main.js"></script>
更改为<script src="/main.js"></script>