下一个js和Apollo-Cookie未通过

red*_* 87 11 javascript apollo reactjs graphql next.js

我正在将Next JS与Apollo结合使用,并在with-data HOC中使用以下配置对其进行了设置:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { withClientState } from 'apollo-link-state';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloLink, Observable, split  } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import withApollo from 'next-with-apollo';
import { SubscriptionClient } from 'subscriptions-transport-ws';

import { endpoint, prodEndpoint, WSendpoint, WSprodEndpoint } from '../config';

import defaults from '../apollo-state/graphql/default-state';
import Mutation from '../apollo-state/resolvers/mutation-resolvers';

const wsClient = process.browser ? new SubscriptionClient(process.env.NODE_ENV === 'development' ? WSendpoint : WSprodEndpoint, {
  reconnect: true,
}) : null;


function createClient({ headers }) {
  const wsLink = process.browser ? new WebSocketLink(wsClient) : null;
  const httpLink = new HttpLink({
    uri: process.env.NODE_ENV === 'development' ? endpoint : prodEndpoint,
    credentials: 'include',
  })

  const link = process.browser ? split(
    // split based on operation type
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === 'OperationDefinition' && operation === 'subscription';
    },
    wsLink,
    httpLink,
  ) : httpLink;

  const cache = new InMemoryCache();

  const request = async operation => {
    const contextObj = {
      fetchOptions: {
        credentials: 'include'
      },
      headers
    };
    operation.setContext(contextObj);
  }; 

  const requestLink = new ApolloLink((operation, forward) =>
    new Observable(observer => {
      let handle;
      Promise.resolve(operation)
        .then(oper => request(oper))
        .then(() => {
          handle = forward(operation).subscribe({
            next: observer.next.bind(observer),
            error: observer.error.bind(observer),
            complete: observer.complete.bind(observer),
          });
        })
        .catch(observer.error.bind(observer));

      return () => {
        if (handle) handle.unsubscribe();
      };
    })
  );
  // end custom config functions
  const apolloClient = new ApolloClient({
      credentials: 'include',
      ssrMode: !process.browser,
      link: ApolloLink.from([
        onError(({ graphQLErrors, networkError }) => {
          if (graphQLErrors) {
            console.log(graphQLErrors)
          }
          if (networkError) {
            console.log(networkError)
          }
        }),
        requestLink,
        withClientState({
          defaults, // default state
          resolvers: {
            Mutation // mutations
          },
          cache
        }),
        link
      ]),
      cache
  }); // end new apollo client
  return apolloClient;
}

export { wsClient };
export default withApollo(createClient);
Run Code Online (Sandbox Code Playgroud)

在本地,一切正常。我可以登录,当我访问该站点时它会自动登录,并且SSR没问题。但是,当我部署到Next或Heroku时,SSR不起作用。

我调查了这个问题,似乎这是一个常见的问题,即Cookie没有随请求一起发送:

https://github.com/apollographql/apollo-client/issues/4455

https://github.com/apollographql/apollo-client/issues/4190

https://github.com/apollographql/apollo-client/issues/4193

问题似乎在于Apollo配置的这一部分,其中有时未定义标头,因此未发送cookie:

  const request = async operation => {
    const contextObj = {
      fetchOptions: {
        credentials: 'include'
      },
      headers
    };
    operation.setContext(contextObj);
  }; 
Run Code Online (Sandbox Code Playgroud)

人们提到的一些解决方法是:如果标题存在,则手动设置cookie标题:

  const request = async operation => {
    const contextObj = {
      fetchOptions: {
        credentials: 'include'
      },
      headers: {
        cookie: headers && headers.cookie
      }
    };
    operation.setContext(contextObj);
  }; 
Run Code Online (Sandbox Code Playgroud)

上面对代码的修改修正了服务器端渲染,但是当我使用浏览器中已登录的cookie访问网站时,它将不再自动登录(它以我的初始方法自动登录,但不会在生产环境中执行SSR )

人们已经提到,这可能与Now或Heroku一起使用,即在部署应用程序后使用生成的URL中的子域,并使用自定义域来解决问题。我尝试使用自定义域,但是仍然遇到问题。我的域设置如下:

前端域:mysite.com后端域:api.mysite.com

这里有没有人遇到过这个问题并能够解决?

如果您发现我的配置有问题或我如何设置域,请告诉我。

Nga*_*ine 2

迟到了,但试试这个

您应该添加 cookies 选项,如下所示。请确保您的浏览器中有一个 cookie,即 csrftoken。它应该是可用的。希望它有效。

  const 请求 = 异步操作 => {
    常量 contextObj = {
      获取选项:{
        凭证:“包括”
      },
      //################ 在此更改 ##########
      标题:{
        ...标头
      }
      饼干: {
        ...饼干
      }
      //########################################

    };
    操作.setContext(contextObj);
  };