react-apollo服务器端渲染

时间:2019-05-18 05:02:13

标签: javascript reactjs apollo react-apollo next.js

免责声明:我在SO上看到了许多其他问题,听起来也一样。但是不,这个问题及其背景,一切都不同。不重复。

嘿,我已经按照 https://github.com/zeit/next.js/tree/canary/examples/with-apollo

除cookie之外,其他所有方法都运行良好。在实施CSR的早期,我的withData.js如下

import withApollo from 'next-with-apollo'
import ApolloClient from 'apollo-boost'
function createClient({ headers }) {

  return new ApolloClient({
    uri: `${process.env.ENDPOINT}/graphql`,
    request: operation => {
      operation.setContext({
        fetchOptions: {
          credentials: 'include',
        },
        headers
      })
    }
  })

}

export default withApollo(createClient)

在上面的示例中,由于request功能,cookie起作用了。

但是在按照Next.js示例的SSR实现中,cookies不起作用。请帮忙。 我需要将next-with-apolloreact-apollo SSR集成在一起。

1 个答案:

答案 0 :(得分:0)

我的整合如下:

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'isomorphic-unfetch';
import withApollo from 'next-with-apollo';

// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) { // eslint-disable-line
  global.fetch = fetch; // eslint-disable-line
}

export default withApollo(
  ({ ctx, headers, initialState }) => {
    return new ApolloClient({
      link: createHttpLink({
        fetch, // Switches between unfetch & node-fetch for client & server.
        uri: process.browser ? '/graphql' : `${process.env.ABSOLUTE_URL}/graphql`, // Only absolute URLs are supported
        credentials: 'same-origin',
        // В режиме SSR необходимо передавать данные авторизации, которые хранятся в cookies, иначе, в браузер будет
        // выдана страница от имени анонимного пользователя несмотря на то, что он может быть авторизован
        headers: process.browser ? {} : {
          cookie: headers.cookie
        }
      }),
      ssrMode: !process.browser, // eslint-disable-line
      //  rehydrate the cache using the initial data passed from the server:
      cache: new InMemoryCache().restore(initialState || {}),
      connectToDevTools: process.browser
    });
  }
);

查看回调参数({ ctx, headers, initialState })-它们来自服务器。

现在,我从CookiesProvider包中的App组件中渲染next/app

<ApolloProvider client={apollo}>
  <CookiesProvider>
    {/* ... */}
  </CookiesProvider>
</ApolloProvider>