Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

reactjs - Invalid response from authorization hook

I'm trying to implement ApolloClient with websockets. My problem was that token was not accutalised in headers, so I used apolloLink in authMiddleware. But now it's not working

import { ApolloClient, InMemoryCache, ApolloLink as x } from '@apollo/client';
import { split, ApolloLink } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { SubscriptionClient } from 'subscriptions-transport-ws';


const cache = () =>
  new InMemoryCache({
    ...
  });

interface Definintion {
  kind: string;
  operation?: string;
}

const httpLink = new HttpLink({
  uri: process.env.REACT_APP_URL,
});

const authMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      authorization: localStorage.getItem('token') || null,
    },
  });
  // Add onto payload for WebSocket authentication
  (operation as any & { authToken: string | undefined }).authToken = localStorage.getItem('token');

  return forward(operation);
});

const socket = new SubscriptionClient(process.env.REACT_APP_URL2 as string, {
  reconnect: true,
});

const webSocketLink: WebSocketLink = new WebSocketLink(socket);

const link = split(
  ({ query }) => {
    const { kind, operation }: Definintion = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  webSocketLink,
  httpLink,
);

const client = new ApolloClient({
  link: authMiddleware.concat(link) as any,
  cache: cache(),
});

I can't do any query because i'm getting error

Error: Invalid response from authorization hook

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...