Contentful SSR React 应用程序在补水后出错
Contentful SSR React App Getting Error after Hydrating
我正在制作一个 SSR React 内容丰富的应用程序,在我正确地滋润应用程序之后,我收到了一个与我从服务器正确获取的数据相关的错误。它认为我传递给 contentful API 的密钥不存在,但它确实存在于服务器请求中。我不太明白为什么会这样抛出这个错误。有没有人 运行 出于显而易见的原因,这里的代码减去了密钥。
https://github.com/JoshBowdenConcepts/goop-troop-collective
当前错误如下所示:
Uncaught TypeError: Expected parameter accessToken
K contentful.js:53
267 client.js:8
l (index):1
100 main.27827bac.chunk.js:1
l (index):1
r (index):1
t (index):1
<anonymous> main.27827bac.chunk.js:1
contentful.js:53:10
干杯,
问题在于,虽然 server-side 呈现的树将 siteInfo
传递给 <App />
,但客户端包的 index.js
不会。如果您 运行 是 React 的开发版本,您可能会看到与水合树相关的错误与 DOM 不同。您需要以某种方式将初始道具传递给客户端 - 一个流行的技巧是将它们注入全局变量并传递它,例如:
服务器:
getSiteInformation().then((info) => {
const siteInfoInjector = `<script>window.__INITIAL_PROPS = ${JSON.stringify(
info.fields
)};</script>`;
return res.send(
data.replace(
'<div id="root"></div>',
`${siteInfoInjector}
<div id="root">
${ReactDOMServer.renderToString(
<App siteInfo={info.fields} />
)}
</div>`
)
);
});
客户的index.js
:
const initialProps = window.__INITIAL_PROPS;
ReactDOM.hydrate(
<React.StrictMode>
<App siteInfo={initialProps} />
</React.StrictMode>,
document.getElementById("root")
);
提醒一句,这会将字符串化结果直接注入 HTML,这意味着如果您的 siteTitle
是 hello </script><script>alert(1)
,您手上就有一个 XSS .解决此问题的一种方法是对初始值进行 base-64 编码:
服务器:
const siteInfoInjector = `<script>window.__INITIAL_PROPS = "${Buffer.from(
JSON.stringify(info.fields)
).toString("base64")}";</script>`;
客户:
const initialProps = JSON.parse(atob(window.__INITIAL_PROPS));
我正在制作一个 SSR React 内容丰富的应用程序,在我正确地滋润应用程序之后,我收到了一个与我从服务器正确获取的数据相关的错误。它认为我传递给 contentful API 的密钥不存在,但它确实存在于服务器请求中。我不太明白为什么会这样抛出这个错误。有没有人 运行 出于显而易见的原因,这里的代码减去了密钥。
https://github.com/JoshBowdenConcepts/goop-troop-collective
当前错误如下所示:
Uncaught TypeError: Expected parameter accessToken
K contentful.js:53
267 client.js:8
l (index):1
100 main.27827bac.chunk.js:1
l (index):1
r (index):1
t (index):1
<anonymous> main.27827bac.chunk.js:1
contentful.js:53:10
干杯,
问题在于,虽然 server-side 呈现的树将 siteInfo
传递给 <App />
,但客户端包的 index.js
不会。如果您 运行 是 React 的开发版本,您可能会看到与水合树相关的错误与 DOM 不同。您需要以某种方式将初始道具传递给客户端 - 一个流行的技巧是将它们注入全局变量并传递它,例如:
服务器:
getSiteInformation().then((info) => {
const siteInfoInjector = `<script>window.__INITIAL_PROPS = ${JSON.stringify(
info.fields
)};</script>`;
return res.send(
data.replace(
'<div id="root"></div>',
`${siteInfoInjector}
<div id="root">
${ReactDOMServer.renderToString(
<App siteInfo={info.fields} />
)}
</div>`
)
);
});
客户的index.js
:
const initialProps = window.__INITIAL_PROPS;
ReactDOM.hydrate(
<React.StrictMode>
<App siteInfo={initialProps} />
</React.StrictMode>,
document.getElementById("root")
);
提醒一句,这会将字符串化结果直接注入 HTML,这意味着如果您的 siteTitle
是 hello </script><script>alert(1)
,您手上就有一个 XSS .解决此问题的一种方法是对初始值进行 base-64 编码:
服务器:
const siteInfoInjector = `<script>window.__INITIAL_PROPS = "${Buffer.from(
JSON.stringify(info.fields)
).toString("base64")}";</script>`;
客户:
const initialProps = JSON.parse(atob(window.__INITIAL_PROPS));