gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:39:48 24 4
gpt4 key购买 nike

我的前端是 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 服务器调用 GraphQL 突变 :3000到 GraphQL :3333 ?

最佳答案

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

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

关于express - 如何从 Express 服务器后端调用 GraphQL 查询/变异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54559928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com