类型 "ID" 的变量“$userId”用于期望类型 "ID!" 的位置

Variable "$userId" of type "ID" used in position expecting type "ID!"

我正在尝试使用 npm 包 graphql-request 发出 graphql 请求。我发现了模板文字的使用。

   async getCandidate(userId: number) {
            const query = gql`
            query($userId: ID){
              candidate(id: $userId){
                id _id source phone
              }
            }
            `
            const variables = {userId: "/api/candidates/" + userId}
            return await request(GRAPHQL_URL, query, variables)
        }

我正在尝试使用 usedId 变量,但出现错误:

Variable "$userId" of type "ID" used in position expecting type "ID!".: {"response":{"errors":[{"message":"Variable \"$userId\" of type \"ID\" used in position expecting type \"ID!\".","extensions":{"category":"graphql"},"locations":[{"line":2,"column":9},{"line":3,"column":19}]}],"status":200},"request":{"query":"\n\t\tquery($userId: ID){\n\t\t  candidate(id: $userId){\n\t\t    id _id source phone\n\t\t  }\n\t\t}\n\t\t","variables":{"userId":"/api/candidates/1"}

你只需要把这个query($userId: ID){修改成这个 query($userId: ID!){

这是因为模式定义 userId 的值需要是 non-nullable。