下一个js和Apollo-Cookie未通过

时间:2019-05-22 19:22:20

标签: javascript reactjs graphql apollo 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);

在本地,一切正常。我可以登录,当我访问该站点时它会自动登录,并且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);
  }; 

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

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

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

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

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

这里的任何人都遇到过该问题并能够解决吗?

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

2 个答案:

答案 0 :(得分:0)

晚些时候尝试一下

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


  const request = async operation => {
    const contextObj = {
      fetchOptions: {
        credentials: 'include'
      },
      //################ CHANGE HERE ##########
      headers: {
        ...header
      }
      cookies: {
        ...cookies
      }
      //######################################

    };
    operation.setContext(contextObj);
  };

答案 1 :(得分:0)

官方NextJs apollo example存在问题或不足 在此issue

中进行了报告

我将汇总一下可以解决此问题的评论

这里是对derozan10发布的官方示例的修改,该官方示例源自mzygmunt的示例前版本的帖子

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import fetch from 'isomorphic-unfetch';
import { endpoint } from '../config';

export default function createApolloClient(initialState, ctx) {
  // The `ctx` (NextPageContext) will only be present on the server.
  // use it to extract auth headers (ctx.req) or similar.

  const enchancedFetch = (url, init) =>
    fetch(url, {
      ...init,
      headers: {
        ...init.headers,
        Cookie: ctx.req.headers.cookie,
      },
    }).then(response => response);

  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: new HttpLink({
      uri: endpoint, // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch: ctx ? enchancedFetch : fetch,
    }),
    cache: new InMemoryCache().restore(initialState),
  });
}

为使其正常工作,我还更改了后端的CORS选项


// a graphql-yoga + prisma 1 backend (Wes Boss' Advanced React class)
...
const cors = require("cors");

const server = createServer();

var corsOptions = {
  origin: process.env.FRONTEND_URL,
  credentials: true
};
server.express.use(cors(corsOptions));
...

我还更新了依赖项,直到达到“无毛线警告”状态

"dependencies": {
    "@apollo/react-hooks": "^3.1.5",
    "@apollo/react-ssr": "^3.1.5",
    "@babel/core": "^7.1.2",
    "@types/react": "^16.8.0",
    "apollo-cache-inmemory": "^1.6.6",
    "apollo-client": "^2.6.9",
    "apollo-link-http": "^1.5.17",
    "apollo-utilities": "^1.3.2",
    "graphql": "14.3.1",
    "graphql-tag": "^2.10.3",
    "isomorphic-unfetch": "^3.0.0",
    "next": "latest",
    "prop-types": "^15.6.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },
  "devDependencies": {
    "babel-plugin-graphql-tag": "^2.5.0"
  }