我正在学习 GraphQL 并且是该技术的新手。我无法找出此语法错误的原因。当我在 graphiql 上对其进行测试时,它会引发意外的 token 语法错误
这是我的 server.js:
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const app = express();
app.get(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true
})
);
app.listen(4000, () => {
console.log("Server listening to port 4000...");
});
这是我的架构:
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema,
GraphQLList,
GraphQLNotNull
} = require("graphql");
// HARD CODED DATA
const customers = [
{ id: "1", name: "John Doe", email: "jdoe@gmail.com", age: 35 },
{ id: "2", name: "Kelly James", email: "kellyjames@gmail.com", age: 28 },
{ id: "3", name: "Skinny Pete", email: "skinnypete@gmail.com", age: 31 }
];
// CUSTOMER TYPE
const CustomerType = new GraphQLObjectType({
name: "Customer",
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString },
age: { type: GraphQLInt }
})
});
// ROOT QUERY
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
customer: {
type: CustomerType,
args: {
id: { type: GraphQLString }
},
resolve(parentValue, args) {
for (let i = 0; i < customers.length; i++) {
if (customers[i].id == args.id) {
return customers[i];
}
}
}
},
customers: {
type: new GraphQLList(CustomerType),
resolve(parentValue, args) {
return customers;
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
有人可以指出我正确的方向吗?我无法弄清楚这里的问题?
最佳答案
根据 express-middleware
的文档,你应该使用 app.use
挂载中间件,而不是 app.get
:
app.use('/graphql', graphqlHTTP({schema, graphiql: true}))
这样做将使 GraphiQL 在浏览器中可用,但也允许您创建
POST
向 /graphql
发出请求端点。通过使用 app.get
,您可以进入GraphiQL 界面,但无法实际制作POST
要求。当您在 GraphiQL 中发出请求时,它会尝试发出 POST
请求到您的端点,但由于您的应用程序未配置为接收它,因此请求失败。您看到的错误是尝试将通用错误表达抛出的缺失路由解析为 JSON 的结果。
关于graphql - 语法错误 : Unexpected token < in JSON at position 0 when testing in Graphiql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897364/