首页 > 解决方案 > React JS 与 Apollo GraphQL 订阅

问题描述

嗨,我正在尝试使用 auth 标头在 apollo 中实现订阅。我一直遇到出现 CORS 错误的问题。

似乎没有办法做到这一点。

这是我对您的代码所做的修改的精简版:

const httpLink = new HttpLink({
  uri: "http://localhost:4444/graphql",
  fetchOptions: {
    credentials: "include"
  },
  request: operation => {
    const token = localStorage.getItem("token");
    operation.setContext({
      headers: {
        Authorization: "Bearer " + token
      }
    });
  },
  onError: ({ networkError }) => {
    if (networkError) {
      console.log("Network Error:::", networkError);
    }
  }
});

const wsLink = new WebSocketLink({
  uri: ws://localhost:4444/subscriptions,
  options: {
    reconnect: true
  }
});

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === "OperationDefinition" && operation === "subscription";
  },
  wsLink,
  httpLink
);

*注意我正在尝试使用 auth 来实现

标签: reactjsgraphqlapollo

解决方案


推荐阅读