使用备用 GraphQL 客户端连接到 Apollo Server
Using an alternative GraphQL client to connect to Apollo Server
是否可以使用非 Apollo 客户端连接到 Apollo GraphQL 服务器,例如 graphql.js - https://github.com/f/graphql.js?
如果可以,应该使用哪个端点?或者有其他方法吗?
失败并出现 HTTP 500
服务器错误:
const graph = graphql('http://localhost:3013/graphql', {
method: 'POST' // POST by default.
});
const res = graph(`query getQuestions {
questions {
id,
question
}
}
`);
res().
then((result) => console.log(result))
.catch((err) => console.log(err));
当然,只要客户端遵循 GraphQL 规范,您就可以使用任何 GraphQL 客户端。
例如
server.ts
:
import { ApolloServer, gql } from 'apollo-server';
import graphql from 'graphql.js';
const typeDefs = gql`
type Query {
_: String
}
`;
const resolvers = {
Query: {
_: () => 'Hello',
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen().then(async ({ url }) => {
console.log(`Apollo server is listening on ${url}graphql`);
const graph = graphql(`${url}graphql`, { asJSON: true });
const helloQuery = graph(`
query {
_
}
`);
const actual = await helloQuery();
console.log('actual: ', actual);
server.stop();
});
输出:
Apollo server is listening on http://localhost:4000/graphql
actual: { _: 'Hello' }
是否可以使用非 Apollo 客户端连接到 Apollo GraphQL 服务器,例如 graphql.js - https://github.com/f/graphql.js?
如果可以,应该使用哪个端点?或者有其他方法吗?
失败并出现 HTTP 500
服务器错误:
const graph = graphql('http://localhost:3013/graphql', {
method: 'POST' // POST by default.
});
const res = graph(`query getQuestions {
questions {
id,
question
}
}
`);
res().
then((result) => console.log(result))
.catch((err) => console.log(err));
当然,只要客户端遵循 GraphQL 规范,您就可以使用任何 GraphQL 客户端。
例如
server.ts
:
import { ApolloServer, gql } from 'apollo-server';
import graphql from 'graphql.js';
const typeDefs = gql`
type Query {
_: String
}
`;
const resolvers = {
Query: {
_: () => 'Hello',
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen().then(async ({ url }) => {
console.log(`Apollo server is listening on ${url}graphql`);
const graph = graphql(`${url}graphql`, { asJSON: true });
const helloQuery = graph(`
query {
_
}
`);
const actual = await helloQuery();
console.log('actual: ', actual);
server.stop();
});
输出:
Apollo server is listening on http://localhost:4000/graphql
actual: { _: 'Hello' }