React Apollo Client not sending cookies

后端 未结 3 1684
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 12:24

I have tried following the instructions on Apollo Client for sending cookies along with the graphql request, but the express server is not receiving any cookies and when I i

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 12:50

    There is a helper from the Apollo Client library called createNetworkInterface and you can import it like so:

    import ApolloClient, { createNetworkInterface } from 'apollo-client';
    

    Then you can implement it like so:

    const networkInterface = createNetworkInterface({
      uri: 
    });
    

    The Apollo Client assumes that your graphql client on the express side is listening on the endpoint /graphql. You can verify this by going to your server.js file.

    You should see something like:

    // Instruct Express to pass on any request made to the '/graphql' route
    // to the GraphQL instance.
    app.use(
      '/graphql',
      expressGraphQL({
        schema,
        graphiql: true
      })
    );
    

    So the uri: option you specify is still GraphQL like so:

    const networkInterface = createNetworkInterface({
      uri: '/graphql'
    });
    

    We do this because whenever we create our own networkInterface it no longer assumes the uri is /graphql so we have to directly say it.

    The part that really matters is the opts: property like so:

    const networkInterface = createNetworkInterface({
      uri: '/graphql',
      opts: {
        credentials: 'same-origin'
      }
    });
    

    This is saying its safe to send along cookies whenever it makes a query to the backend server. So you take this networkInterface and pass it along to the Apollo Client like so:

    const networkInterface = createNetworkInterface({
      uri: '/graphql',
      opts: {
        credentials: 'same-origin'
      }
    });
    
    const client = new ApolloClient({
      networkInterface,
      dataIdFromObject: o => o.id
    });
    

    So that is pretty much it for getting Apollo to send along cookies along with every single request it makes to the backend.

提交回复
热议问题