首页 > 解决方案 > 如何修复 graphql 错误:必须提供文件?

问题描述

我正在使用graphql-yoga。我的查询在 GraphiQL 和 curl 中有效,但在 React 中发送时无效。

这是我收到的错误:

Error: Must provide document
    at invariant (.../node_modules/graphql/jsutils/invariant.js:21:11)
    at Object.validate (.../node_modules/graphql/validation/validate.js:53:41)
    at doRunQuery (.../node_modules/apollo-server-core/dist/runQuery.js:111:42)
    at .../node_modules/apollo-server-core/dist/runQuery.js:21:56
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
    at async Promise.all (index 0)

当我发送 CURL 时,它可以工作:

curl 'http://localhost:4000/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:4000' -H 'Authorization: XXX' --data-binary '{"query":"query { get_me { user { email } }}"}' --compressed

但是当我将它添加到 React 应用程序时,它不会:

export const myQuery = () => ({
  url: 'http://localhost:4000/graphql',

  options: {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'ABC',
    },
  },

  body: {
    data: '{"query":"get_user { user { email } }"}',
  },

标签: graphqlreact-apollographql-jsapollo-server

解决方案


我发现了问题:我应该使用

body: {
    query: 'query { get_user { user { email } } }',
  },

代替

body: {
    data: '{"query":"get_user { user { email } }"}',
  },

推荐阅读