Vuejs2 Vue apollo-通过WebSocket发送授权

Vuejs2 Vue apollo-通过WebSocket发送授权,vuejs2,graphql,hasura,vue-apollo,Vuejs2,Graphql,Hasura,Vue Apollo,我有一个vue web应用程序,我正试图从中使用hasura查询运行订阅 我的问题是,我无法像后端所期望的那样向Websocket请求传递授权令牌。 以下是我当前的设置: const token = localStorage.getItem("token") || null; const options = { httpUri: //graphql http entpoint, wsUri: //graphql ws endpoint }; let link = n

我有一个vue web应用程序,我正试图从中使用hasura查询运行订阅

我的问题是,我无法像后端所期望的那样向Websocket请求传递授权令牌。 以下是我当前的设置:

const token = localStorage.getItem("token") || null;

const options = {
  httpUri: //graphql http entpoint,
  wsUri: //graphql ws endpoint
};
let link = new HttpLink({
  uri: options.httpUri
});

// Create the subscription websocket link if available
if (options.wsUri) {
  const wsLink = new WebSocketLink(
    new SubscriptionClient(options.wsUri, {
      lazy: true,
      reconnect: true,
      connectionParams: {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    })
  );

  // using the ability to split links, you can send data to each link
  // depending on what kind of operation is being sent
  link = split(
    // split based on operation type
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
    wsLink,
    link
  );
}

const authLink = setContext((_, { headers }) => {
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message }) => {
      if (message.includes("unauthorized")) {
        EventBus.$emit("unauthorized");
      }
    });

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const apolloClient = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, link]),
  cache: new InMemoryCache(),
  connectToDevTools: true
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
});
当我尝试运行订阅时,我得到

HTTP认证失败;没有可用的有效凭据

在ws-request标头中,我看不到我的授权承载集


我需要对http和ws请求进行授权的侧信息

我认为
errorLink
authLink
会意外更改websocket头标记。您尝试稍微修改一下:

const httpLink=from([
authLink,
//错误链接,
新HttpLink({
uri:Config.httpDataHost,
标题:{
[XHasuraClientName]:Config.hasuraClientName
}
})
]);
const wsLink=新的WebSocketLink({…});
常量链接=。。。
const Apollo客户端=新Apollo客户端({
链接:ApolloLink.from([errorLink,link]),
缓存:新的InMemoryCache(),
connectToDevTools:true

});
我尝试注释
错误链接
,但仍然没有发送到ws-request的头,从未调用
connectionParams
函数身份验证后是否运行订阅?直到第一次使用
lazy
optionies的订阅调用,订阅才会运行,我发现了问题-我在docker内部使用hasura引擎,nginx作为hasura实例的反向代理,所以我必须在nginx配置文件中创建一个指向内部docker hasura引擎的路由,但您的github示例确实有所帮助,非常感谢