我刚用apollo Graphql为SSR创建了一个expressJs服务器。我有这个问题:页面启动后页面的源是预期的,但在服务器运行之前,Graphql提取的数据永远不会改变。
我目前正在使用http://fake.graphql.guru/graphql来获取一些模拟数据,并且每个请求随机都会有数据更改。
遵循expressjs和apolloClient配置的代码
// express js
app.get('*', (req, res, next) => {
renderToStringWithData(<StaticRouter location={req.url} context={{}}><App /></StaticRouter>).then((content) => {
const initialState = client.extract();
res.status(200);
res.setHeader('Cache-Control', 'no-cache');
res.send(Template({
content,
state: initialState,
}));
next();
});
});
// apollo client
const client = new ApolloClient({
ssrMode: true,
link: new HttpLink({
fetch,
uri: 'http://fake.graphql.guru/graphql',
}),
cache: new InMemoryCache().restore(process.env.NODE_ENV !== 'PROD' ?
window.__APOLLO_STATE__ : null),
defaultFetchPolicy: 'network-only',
ssrForceFetchDelay: 100,
});
因此,我对每个请求的期望是服务器返回带有新数据的新html页面。怎么了?
我找到了一个解决方案:为每个请求重置客户端的缓存就足以调用client.resetStore()
app.get('*', (req, res, next) => {
// reset the client cache
client.resetStore();
renderToStringWithData(<StaticRouter location={req.url} context={{}}>
<ReactApp /></StaticRouter>).then((content) => { // eslint-disable-line
const initialState = client.extract();
res.status(200);
res.setHeader('Cache-Control', 'no-cache');
res.send(Template({
content,
state: initialState,
}));
next();
});
});