graphql / graphiql

GraphiQL & the GraphQL LSP Reference Ecosystem for building browser & IDE tools.
MIT License
16.08k stars 1.72k forks source link

graphiQL doesn't pick tokens from the headers... common issue? #680

Open RoniFinTech opened 6 years ago

RoniFinTech commented 6 years ago

This is a POST request and I see the tokens are valid... but graphiql doesn't pick those tokens when I run a query.

screen shot 2018-05-19 at 11 08 01 pm

Here is my code for setting and getting tokens from the headers...


import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloProvider } from 'react-apollo';
import { setContext } from 'apollo-link-context';
import { ApolloLink } from 'apollo-link';
import 'semantic-ui-css/semantic.min.css';

import Routes from './routes';
import registerServiceWorker from './registerServiceWorker';

const httpLink = createHttpLink({ uri: 'http://localhost:8081/graphql' });

const middlewareLink = setContext(() => ({
  headers: {
    'x-token': localStorage.getItem('token'),
    'x-refresh-token': localStorage.getItem('refreshToken'),
  },
}));

const afterwareLink = new ApolloLink((operation, forward) => {
  const { headers } = operation.getContext();

  if (headers) {
    const token = headers.get('x-token');
    const refreshToken = headers.get('x-refresh-token');

    if (token) {
      localStorage.setItem('token', token);
    }

    if (refreshToken) {
      localStorage.setItem('refreshToken', refreshToken);
    }
  }

  return forward(operation);
});

const link = afterwareLink.concat(middlewareLink.concat(httpLink));

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

const App = (
  <ApolloProvider client={client}>
    <Routes />
  </ApolloProvider>
);

ReactDOM.render(App, document.getElementById('root'));
registerServiceWorker();

I downladed GrapihQL.app for my macbook and added tokens under "Edit HTTP Headers" and it worked fine...

Is this a graphiql issue? I'm using Chrome Version 63.0.3239.84 and tried on Windows and iOS... same issue...

sebastienva commented 6 years ago

Where come from your graphiql ? Graphiql.app is an app that includes graphiql and provides headers support, this not a raw graphiql. You can see an example of graphiql usage here. You must provide a fetcher and handle your headers manually.