Генератор кода GraphQL - не удается загрузить схему GQL с конечной точки сервера Nestjs

Я использую генератор кода graphQL в приложении angular, и я пытаюсь загрузить свою схему из локального приложения nestjs.

Вот файл codegen.yml:

schema: http://localhost:3000/graphql
documents: ./src/app/graphql/**/*.graphql
generates:
  ./src/app/graphql/types.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-apollo-angular

Когда я запускаю graphql-codegen, я получаю следующую ошибку:

 Failed to load schema from http://localhost:3000/graphql:

        invalid json response body at http://localhost:3000/graphql reason: Unexpected token < in JSON at position 0
        FetchError: invalid json response body at http://localhost:3000/graphql reason: Unexpected token < in JSON at position 0
    at C:\ngWishList2\node_modules\node-fetch\lib\index.js:271:32
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
    at async UrlLoader.load (C:\ngWishList2\node_modules\@graphql-toolkit\url-loader\index.cjs.js:87:22)
    at async C:\ngWishList2\node_modules\@graphql-toolkit\core\index.cjs.js:682:25        
    at async Promise.all (index 5)
    at async loadSingleFile (C:\ngWishList2\node_modules\@graphql-toolkit\core\index.cjs.js:678:5)
    at async C:\ngWishList2\node_modules\@graphql-toolkit\core\index.cjs.js:556:38        
    at async Promise.all (index 0)
    at async loadTypedefs (C:\ngWishList2\node_modules\@graphql-toolkit\core\index.cjs.js:620:5)
    at async Object.loadSchema (C:\ngWishList2\node_modules\@graphql-toolkit\core\index.cjs.js:705:21)
    at async loadSchema (C:\ngWishList2\node_modules\@graphql-codegen\cli\bin.js:342:24)  
    at async C:\ngWishList2\node_modules\@graphql-codegen\cli\bin.js:704:55
    at async Task.task (C:\ngWishList2\node_modules\@graphql-codegen\cli\bin.js:567:17)   

        GraphQL Code Generator supports:
          - ES Modules and CommonJS exports (export as default or named export "schema")  
          - Introspection JSON File
          - URL of GraphQL endpoint
          - Multiple files with type definitions (glob expression)
          - String in config file

        Try to use one of above options and run codegen again.
    Error: Failed to load schema
        at loadSchema (C:\ngWishList2\node_modules\@graphql-codegen\cli\bin.js:353:15)    
        at processTicksAndRejections (internal/process/task_queues.js:94:5)
    Error: Failed to load schema
        at loadSchema (C:\ngWishList2\node_modules\@graphql-codegen\cli\bin.js:353:15)    
        at processTicksAndRejections (internal/process/task_queues.js:94:5)

Когда я регистрирую ответ, я вижу, что он пытается проанализировать следующее, что объясняет ошибку:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /graphql</pre>
</body>
</html>

Если я копаюсь в index.cjs.cs и регистрирую сгенерированное тело POST и ответ, я получаю:

ТЕЛО:

{"query":"query IntrospectionQuery {\n  __schema {\n    queryType {\n      name\n    }\n  
  mutationType {\n      name\n    }\n    subscriptionType {\n      name\n    }\n    types 
{\n      ...FullType\n    }\n    directives {\n      name\n      description\n      locations\n      args {\n        ...InputValue\n      }\n    }\n  }\n}\n\nfragment FullType on __Type {\n  kind\n  name\n  description\n  fields(includeDeprecated: true) {\n    name\n   
 description\n    args {\n      ...InputValue\n    }\n    type {\n      ...TypeRef\n    }\n    isDeprecated\n    deprecationReason\n  }\n  inputFields {\n    ...InputValue\n  }\n  
interfaces {\n    ...TypeRef\n  }\n  enumValues(includeDeprecated: true) {\n    name\n    
description\n    isDeprecated\n    deprecationReason\n  }\n  possibleTypes {\n    ...TypeRef\n  }\n}\n\nfragment InputValue on __InputValue {\n  name\n  description\n  type {\n    
...TypeRef\n  }\n  defaultValue\n}\n\nfragment TypeRef on __Type {\n  kind\n  name\n  ofType {\n    kind\n    name\n    ofType {\n      kind\n      name\n      ofType {\n        kind\n        name\n        ofType {\n          kind\n          name\n          ofType {\n  
          kind\n            name\n            ofType {\n              kind\n
name\n              ofType {\n                kind\n                name\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n","variables":{},"operationName":"IntrospectionQuery"}

ОТВЕТ:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: true,
      _transformState: [Object]
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'http://localhost:3000/graphql',
    status: 404,
    statusText: 'Not Found',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

Это имело бы смысл, если бы моя конечная точка была неправильной, но если я попробую этот точный запрос в почтальоне, я получу правильный ответ:

Есть идеи, почему это так? Что еще я могу проверить?

Спасибо

5 ответов

ваш сервер graphql работает? У меня была такая же проблема, и я обнаружил, что не запускал свой сервер перед запуском команды

      yarn gen

У меня был неправильный путь для моего schema:установлен в моем файле codegen.yml. Убедитесь, что путь указан правильно.

Это может быть вызвано неправильным Content-Typeили кодирование. Есть ли где-нибудь репродукция этого номера? репо, которое его воспроизводит?

Была такая же проблема. Основная причина заключалась в том, что сервер localhost прослушивал только интерфейс ipv6, поэтому мне пришлось явно объявить в конфигурации codegen — «http://::1:8000/grapql».

Просто хотел поделиться тем, что если ваш проект запускается в контейнере, это может быть проблема с сетью, связанная с докером. В настоящее время я запускаю свой проект локально в контейнере узла + vite.

Мой сервер GraphQL запускается в отдельном контейнере от внутреннего проекта.

Пришлось обновить файл codegen.yaml для чтения

      schema: http://host.docker.internal:8000/graphql
Другие вопросы по тегам