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

时间:2019-02-06 18:05:18

标签: express graphql apollo 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
});

以下似乎是正确的方向,但我得到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);
  });

This post mentions Apollo as the solution,但没有给出示例。

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

4 个答案:

答案 0 :(得分:1)

当您使用require而不是import获得 ApolloClient 时,我认为您缺少此部分:

// es5 or Node.js
const Boost = require('apollo-boost');
const ApolloClient = Boost.DefaultClient;

const ApolloBoost = require('apollo-boost');
const ApolloClient = ApolloBoost.default;

尝试其中一种,看看是否可行。

答案 1 :(得分:1)

这更可能是您要查找的内容:

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

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

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

// 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);
});

从此帖子中摘录的内容可能对其他人也有帮助:https://blog.apollographql.com/4-simple-ways-to-call-a-graphql-api-a6807bcdb355

答案 2 :(得分:0)

您可以使用graphql-request,它是一个简单的GraphQL客户端。

const { request } = require('graphql-request');

request('http://localhost:3333/graphql', `mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

它还支持CORS。

const { GraphQLClient } = require('graphql-request');

const endpoint = 'http://localhost:3333/graphql';
const client = new GraphQLClient(endpoint, {
  credentials: 'include',
  mode: 'cors'
});

client.request(`mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

我用它来进行端到端测试。

答案 3 :(得分:0)

我想添加另一种从express查询的方法。 这就是我最终的目的。

安装必需的软件包

npm install graphql graphql-tag isomorphic-fetch

在单独的文件(myQuery.js)上写graphql

const gql = require('graphql-tag');
const query = gql`
    query($foo: String) {
      // Graphql query
    }
}

主文件

const { print } = require('graphql/language/printer');
const query = require('./myQuery');
require('isomorphic-fetch');

// other logic

const foo = "bar"
const token = "abcdef"

await fetch('https://example.com/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'authorization': `Bearer ${token}`,
    },
    body: JSON.stringify({ 
      query: `${print(query)}`,
      variables: { foo },
    }),
})