简体   繁体   English

react-apollo 服务器端渲染

[英]react-apollo Server Side Rendering

Disclaimer: I saw many other questions on SO which sound the same.免责声明:我在 SO 上看到了许多其他听起来相同的问题。 But no, this question and its context, everything is different.但是不,这个问题及其上下文,一切都不同。 NOT DUPLICATE.不重复。

Hey, I have setup everything as per https://github.com/zeit/next.js/tree/canary/examples/with-apollo .嘿,我已经按照https://github.com/zeit/next.js/tree/canary/examples/with-apollo设置了一切。

Everything works well except cookies.除了饼干,一切都很好。 Earlier in CSR implementation, my withData.js looked like this 👇在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)

In the above example, cookies worked due to the request function.在上面的例子中,cookie 由于request功能而起作用。

But in the SSR implementation as per Next.js example, cookies don't work.但是在按照 Next.js 示例的 SSR 实现中,cookie 不起作用。 Please help.请帮忙。 I need to integrate next-with-apollo with react-apollo SSR.我需要将next-with-apolloreact-apollo SSR 集成。

My integration is following:我的整合如下:

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
    });
  }
);

Look at callback params ({ ctx, headers, initialState }) — they go from server.查看回调参数({ ctx, headers, initialState }) — 它们来自服务器。

Now I render CookiesProvider in App component from next/app package:现在我在来自next/app包的App组件中呈现CookiesProvider

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

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

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