如何从Express服务器后端调用GraphQL查询/变异?

Cha*_*ith 9 express apollo graphql apollo-client

我的前端是localhost:3000,我的GraphQL服务器是localhost:3333.

我已经使用react-apollo在JSX中查询/变异,但还没有从Express中查询/变异.

我想在我的网站上进行查询/变异server.js.

server.get('/auth/github/callback', (req, res) => {
  // send GraphQL mutation to add new user
});
Run Code Online (Sandbox Code Playgroud)

下面似乎是正确的方向,但我得到TypeError: ApolloClient is not a constructor:

const express = require('express');
const next = require('next');
const ApolloClient = require('apollo-boost');
const gql = require('graphql-tag');


// setup
const client = new ApolloClient({
  uri: 'http://localhost:3333/graphql'
});
const app = next({dev});
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    server.get('/auth/github/callback', (req, res) => {
      // GraphQL mutation
      client.query({
        query: gql`
          mutation ADD_GITHUB_USER {
            signInUpGithub(
              email: "email@address.com"
              githubAccount: "githubusername"
              githubToken: "89qwrui234nf0"
            ) {
              id
              email
              githubToken
              githubAccount
            }
          }
        `,
      })
        .then(data => console.log(data))
        .catch(error => console.error(error));
    });

    server.listen(3333, err => {
      if (err) throw err;
      console.log(`Ready on http://localhost:3333`);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });
Run Code Online (Sandbox Code Playgroud)

这篇文章提到阿波罗作为解决方案,但没有给出一个例子.

如何调用从Express服务器:3000到GraphQL 的GraphQL变异:3333

小智 3

这更有可能是您正在寻找的:

const { createApolloFetch } = require('apollo-fetch');

const fetch = createApolloFetch({
    uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});


// Example # 01
fetch({
    query: '{ posts { title } }',
}).then(res => {
    console.log(res.data);
});


// Example # 02
// You can also easily pass variables for dynamic arguments
fetch({
    query: `
        query PostsForAuthor($id: Int!) {
            author(id: $id) {
                firstName
                posts {
                    title
                    votes
                }
            }
        }
    `,
    variables: { id: 1 },
}).then(res => {
    console.log(res.data);
});
Run Code Online (Sandbox Code Playgroud)

摘自这篇文章,可能对其他人也有帮助:https://www.apollographql.com/blog/graphql/examples/4-simple-ways-to-call-a-graphql-api/