mobxjs / mst-gql

Bindings for mobx-state-tree and GraphQL
MIT License
681 stars 81 forks source link

How to add HTTP header to one request? #421

Open michal-wierzba opened 1 year ago

michal-wierzba commented 1 year ago

How to add HTTP header to one request?

Aryk commented 1 year ago
    // Authenticate the network into the current app, save the token for future API calls.
    setAuthorizationHeader(token: string) {
      const env = getEnv(self);

      if (token) {
        // https://github.com/mobxjs/mst-gql/issues/82#issuecomment-535046885
        env.gqlHttpClient.setHeaders({authorization: token});

        env.gqlWsClient.updateOptions({
          uri: constants.wsApiUrl + `?authorization=${token}`,
          // debugIncomingMessages: true,
        });

        // https://github.com/axios/axios#custom-instance-defaults
        env.uploadClient.defaults.headers.common['Authorization'] = token;
      } else {
        env.gqlHttpClient.setHeaders({});
        env.gqlWsClient.updateOptions({
          uri: constants.wsApiUrl,
          // debugIncomingMessages: true,
        });
        delete env.uploadClient.defaults.headers.common['Authorization']
      }
    },

Here is how I did it...does that help?