GraphQL 查询在 React 中未成功获取

我尝试在 React 中使用 GraphQL


useQuery像这样的API:



    const {loading, data, error} = useQuery<BaseUser, BaseUserVars>(

        GET_DASHBOARD_USER, 

        {variables: {id: "1"}}

    )


在我的 API 文件夹中,我保存了所需的接口和查询,如下所示:


export interface BaseUser {

    id: string 

    username: string

    age: number

    goal: Goal

    tasks: [{

      id: string, 

      description: string,

      completedAt: string | null,

      expirationDate: string

    }]


}


export interface BaseUserVars {

    id: string

}


export const GET_DASHBOARD_USER = gql`

    query userWithTasks($id: String!){

    user(id: $id){

    id 

    username

    biography

    goal

    tasks {

     id

     description

     completedAt

     expirationDate

    }

    }

  }`

400 bad response当我运行查询时出现错误。我尝试调用一个函数,我在后端解析器中定义了该函数,称为userWithTask


在操场上,我在没有query关键字的情况下使用了它,效果很好:


{

  userWithTasks(id: "1"){

    id 

    username

    biography

    goal

    tasks {

     id

     description

     completedAt

     expirationDate

    }

  }

}

语法应该是正确的,请问是什么问题?


更新:


这是我收到的错误消息Cannot query field "user" on type "Query". Did you mean "users"?


这是我的后端解析器供参考:


 @Query(() => User)

  async userWithTasks(@Args("id") id: string): Promise<User> {

    const user = await this.userService.getUserByIdWithTasks(id);

    console.log(user)

    return user

  }


慕神8447489
浏览 80回答 1
1回答

慕村9548890

您的查询字段中不存在用户。在 Playground 中,您调用 userWithTasks 而不是 user。当您在 gql 中发出请求时,您必须首先使用键入的参数“复制”字段,然后使用参数值“复制”字段。&nbsp; export const GET_DASHBOARD_USER = gql`&nbsp; &nbsp; &nbsp; &nbsp; query userWithTasks($id: String!){&nbsp; &nbsp; &nbsp; &nbsp; userWithTasks(id: $id){&nbsp; &nbsp; &nbsp; &nbsp; id&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; username&nbsp; &nbsp; &nbsp; &nbsp; biography&nbsp; &nbsp; &nbsp; &nbsp; goal&nbsp; &nbsp; &nbsp; &nbsp; tasks {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;description&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;completedAt&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;expirationDate&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }`
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript