【问题标题】:Node Fetch Post Request using Graphql Query使用 Graphql 查询的节点获取发布请求
【发布时间】:2017-11-20 11:23:09
【问题描述】:

我正在尝试使用 GraphQL 查询发出 POST 请求,但它返回错误 Must provide query string,即使我的请求在 PostMan 中有效。

这是我在 PostMan 中的运行方式:

这是我在应用程序中运行的代码:

const url = `http://localhost:3000/graphql`;    
return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: `
    {
      users(name: "Thomas") { 
        firstName
        lastName 
      } 
    }
  `
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

任何想法我做错了什么?是否可以使我通过fetch 请求传递的正文属性格式化为Text,就像我在 PostMan 请求正文中指定的那样?

【问题讨论】:

    标签: javascript node.js express graphql node-fetch


    【解决方案1】:

    正文应具有query 属性,其中包含查询字符串。也可以传递另一个 variable 属性,以便为查询提交 GraphQL 变量。

    这应该适用于您的情况:

    const url = `http://localhost:3000/graphql`;
    const query = `
      {
        users(name: "Thomas") { 
          firstName
          lastName 
        } 
      }
     `
    
    return fetch(url, { 
      method: 'POST',
      Header: {
         'Content-Type': 'application/graphql'
      }
      body: query
    })
    .then(response => response.json())
    .then(data => {
      console.log('Here is the data: ', data);
      ...
    });
    

    这是提交 GraphQL 变量的方法:

    const query = `
      query movies($first: Int!) {
        allMovies(first: $first) {
          title
        }
      }
    `
    
    const variables = {
      first: 3
    }
    
    return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({query, variables})
    })
    .then(response => response.json())
    .then(data => {
      return data
    })
    .catch((e) => {
      console.log(e)
    })
    

    我创建了a complete example on GitHub

    【讨论】:

    • 感谢您分享此解决方案。但是,在第一个示例中,我必须修改 'Content-Type': 'application/graphql'。就我而言,这是在headers 属性内。所以,fetch 看起来像... fetch("/graphql", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query } ), })
    • 如果我收到错误消息怎么办:“消息:“您无权进行此调用。”?向 graphql 端点发出 fetch 请求时如何授权?
    猜你喜欢
    • 2021-07-08
    • 1970-01-01
    • 2016-06-19
    • 2021-07-09
    • 1970-01-01
    • 2020-06-20
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多