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

12

我的前端是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);
  });

这篇文章提到了Apollo作为解决方案,但没有给出示例。

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


嗨Chance,你能详细解释一下你的问题吗?我不明白...你说过你使用了 react-apollo(React端...),但是现在你不知道如何从React中查询?我不太明白。 - JV Lobo
服务器端渲染 - Şivā SankĂr
嘿,@JVLobo - 我更新了我的问题。 - Chance Smith
很酷,现在更清晰了 :) 我已经发布了一个答案,希望能有所帮助。 - JV Lobo
我不会使用完整功能的客户端来执行服务器端请求。你可以使用一些非常简单的工具,例如graphql-request - Thomas Hennes
4个回答

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

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


如果还有人在使用,apollo-fetch现在已经正式弃用,将不再接收未来的更新。因此,我建议不要遵循这个答案。这使得fetchaxios或者甚至是graphql-request成为可能的最佳替代方案之一。就我个人而言,我更倾向于使用Prisma的graphql-request - sgarcia.dev

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

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


0

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

尝试其中一个并查看是否有效。


第二个方法起作用了,但现在它正在寻找一个“fetch”:错误: 未找到全局的fetch并且没有传递fetcher,要修复,请传递一个适用于您的环境的fetch,例如https://www.npmjs.com/package/node-fetch。>>>例如:import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http'; - Chance Smith
我现在正在深入研究这个... https://www.apollographql.com/docs/link/links/http.html - Chance Smith
我该如何使用 createHttpLink - Chance Smith
我猜像 const HttpLink = require("apollo-link-http").HttpLink; 或者 const { HttpLink } = require('apollo-link-http'); 这样的代码应该可以实现。 - JV Lobo

0
我想添加一种从Express查询的方法。这就是我最终得出的结果。
安装所需的软件包。
npm install graphql graphql-tag isomorphic-fetch

将 GraphQL 写在单独的文件中(myQuery.js)

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 },
    }),
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接