我已经在graphql
中建立了一个apollo-server-express
服务器。我可以使用apollo playground
发送请求并获得响应。我在操场上发送的请求是
{
query: me {username}
}
,我可以在右侧面板上获得预期的响应。但是我很难用apollo-client
建立客户。下面是源代码:
const gql = require('graphql-tag');
const ApolloClient = require('apollo-boost').default;
const fetch = require('node-fetch').default;
const client = new ApolloClient({
uri: 'http://localhost:8000/graphql',
fetch
});
client
.query({
query: gql`
query me {
username
}
`
})
.then(data => console.log(data))
.catch(error => console.error(error));
运行上述代码时,我收到400
错误响应。以下是完整的错误消息。我是graphql的新手,我的代码出什么问题了?
name: 'ServerError',
response:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: [Object],
[Symbol(Response internals)]: [Object] },
statusCode: 400,
result: { errors: [Array] } },
message:
'Network error: Response not successful: Received status code 400',
如果我将查询更改为query : me {
,则会出现以下错误:raphQLError: Syntax Error: Expected {, found : at syntaxError ...
服务器代码为:
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const app = express();
const schema = gql`
type Query {
me: User
}
type User {
username: String!
}
`;
const resolvers = {
Query: {
me: () => {
return {
username: 'Robin Wieruch'
};
}
}
};
const server = new ApolloServer({
typeDefs: schema,
resolvers,
});
server.applyMiddleware({ app, path: '/graphql' });
app.listen({ port: 8000 }, () => {
console.log('Apollo Server on http://localhost:8000/graphql');
});