简体   繁体   English

在服务器端的react-router中使用basename

[英]Use basename in react-router on server side

I'm serving my site from /clientpanel directory on my server. 我正在服务器上的/clientpanel目录中提供我的站点。 So my url is http://xxx.yy/clientpanel . 所以我的网址是http://xxx.yy/clientpanel This is my client-side code: 这是我的客户端代码:

const history = useRouterHistory(createHistory)({
    basename: "/clientpanel"
});

render(
    <Router history={history} routes={routes}/>,
    document.getElementById("root")
);

On client-side everything works just fine. 在客户端,一切正常。 All urls are relative to /clientpanel , but I have problem on how to get this work on server. 所有网址都与/clientpanel ,但我对如何在服务器上运行这个问题有/clientpanel This is my server-side code: 这是我的服务器端代码:

const history = useRouterHistory(createMemoryHistory)({
    basename: "/clientpanel"
});

match({ routes, location: req.url, history}, (error, redirectLocation, renderProps) => {
    if (renderProps) {
        const html = renderToString(
            <RouterContext {...renderProps}/>
        );

        res.send(renderFullPage(html))
    }
});

On first page load I need to omit /clientpanel in url to get this work, but then on client-side after clicking first <Link> /clientpanel is added to the begining. 在第一页加载时,我需要在url中省略/clientpanel以使其工作,但是在第一次单击<Link> /clientpanel之后在客户端添加到/clientpanel How to make it works consistent on both client and server side? 如何使它在客户端和服务器端都能保持一致?

I finally got it to work with the following code: 我终于使用以下代码:

const basename = '/foo'
const location = req.url.replace(basename, '')
// createMemoryHistory from the history package
const history = useRouterHistory(() => createMemoryHistory(location))({ basename })

match({ history, routes, location }, (error, redirectLocation, renderProps) => {

EDIT 编辑

Even better: 更好的是:

const basename = '/foo'
const location = req.url.replace(basename, '')
// createMemoryHistory from the react-router package
const history = createMemoryHistory({ entries: [location], basename })

match({ history, routes, location }, (error, redirectLocation, renderProps) => {

您需要提供匹配的基本名称:

match({ routes, location: req.url, basename: "/clientpanel" }, ...)

const history = createMemoryHistory({ entries: [location], basename }) const history = createMemoryHistory({entries:[location],basename})

This doesn't work because createMemoryHistory doesn't have parameter basename.. The link will be different between client side and server side 这不起作用,因为createMemoryHistory没有参数basename ..客户端和服务器端之间的链接会有所不同

I got a solution in the server side by replacing createHref like this : 通过替换createHref,我得到了服务器端的解决方案:

import { createPath } from 'history/PathUtils';
[...]
history.createHref = location => '/' + language + createPath(location);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM