首页 > 解决方案 > “消息”:“位置 0 的 JSON 中的意外令牌 <”,“堆栈”:“SyntaxError:位置 0 的 JSON 中的意外令牌 <”

问题描述

const express = require('express');
const {graphqlHTTP} = require('express-graphql');
const schema = require('./schema/schema');

const app = express();

app.get('/graphql', graphqlHTTP({
    graphiql:true,
    schema: schema
}))

app.listen(4000,()=>{
    console.log("listining to port 4000..")
}) 

const graphql = require('graphql');

const{
    GraphQLObjectType,
    GraphQLID,
    GraphQLString,
    GraphQLInt,
    GraphQLSchema
} = graphql

const UserType = new GraphQLObjectType({
    name: 'user',
    description: 'Documentation for User...',
    fields: ()=>({
        id: {type: GraphQLString},
        name: {type: GraphQLString},
        age: {type: GraphQLInt}
    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    description: 'description',
    fields: {
        user: {
            type: UserType,
            args: {id: {type: GraphQLString}},
            resolve(parent,args){
                let user = {
                    id: '345',
                    age: 34,
                    name: 'Aman'
                }
                return user;
            }      
        }
    }
});

module.exports = new GraphQLSchema({
    query: RootQuery
})

以上是我的代码,我收到此错误:

“消息”:“位置 0 的 JSON 中的意外令牌 <”,
“堆栈”:“SyntaxError:位置 0 的 JSON 中的意外令牌 <”

谁能告诉我如何解决这个错误?提前致谢。

标签: graphql

解决方案


这种似乎您在客户端应用程序上看到此错误?附带说明一下,您没有添加太多细节,说明您正在做什么以获取此错误,您在哪里看到它,以及您认为是什么导致它,所以我只能放弃您提供的内容就您的设置而言。

这似乎是您从您期望 JSON 的服务器获得 HTML 响应。通常,使用 GraphQL 可能会发生这种情况,因为您发送的是 GET 请求(这可能会打开 GraphiQL 资源管理器)而不是 POST 请求。

您的 GraphQL 客户端代码应该发出一个 POST 请求,并且您应该确保它发送一个标头来接受application/json响应。


推荐阅读