【问题标题】:How to call a GraphQL query/mutation from an Express server backend?如何从 Express 服务器后端调用 GraphQL 查询/突变?
【发布时间】:2019-06-30 18:40:41
【问题描述】:

我的前端是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,但没有举例。

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

【问题讨论】:

  • 您好 Chance,您能详细解释一下您的问题吗?我不明白...您说您使用过react-apollo(React 方面...)但是您不知道如何从 React 查询?我不明白。
  • 嘿,@JVLobo - 我更新了我的问题。
  • 酷,现在更清楚了:) 我已经发布了答案,希望对您有所帮助
  • 我不会使用功能齐全的客户端来执行服务器端请求。你可以使用像graphql-request 这样非常简单的东西来代替。

标签: express graphql apollo apollo-client


【解决方案1】:

我想再添加一种从 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 },
    }),
})

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • 对于仍然存在的任何人,apollo-fetch 现在是 officially deprecated 并且将不再接收未来的更新? 所以我建议不要遵循这个答案。这使得fetchaxios 甚至graphql-request 成为可能的最佳替代方案。就个人而言,我更倾向于 Prisma 的graphql-request
    【解决方案3】:

    您可以使用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));
    

    我用它来做 E2E 测试。

    【讨论】:

      【解决方案4】:

      当您使用 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;
      

      尝试其中一种,看看它是否有效。

      【讨论】:

      • 第二个成功了,但现在它正在寻找fetchError: fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like https://www.npmjs.com/package/node-fetch. >>> For example: import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http';
      • 我现在正在研究这个...apollographql.com/docs/link/links/http.html
      • 我怎样才能要求createHttpLink
      • 我想const HttpLink = require("apollo-link-http").HttpLink;const { HttpLink } = require('apollo-link-http'); 应该这样做
      猜你喜欢
      • 2020-09-11
      • 2019-08-03
      • 2018-11-10
      • 2019-03-20
      • 2019-06-22
      • 2019-05-26
      • 2018-09-17
      • 2017-05-16
      • 2020-04-18
      相关资源
      最近更新 更多