使用Graphql查询的节点获取发布请求 [英] Node Fetch Post Request using Graphql Query

查看:100
本文介绍了使用Graphql查询的节点获取发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过GraphQL查询发出POST请求,但返回错误必须提供查询字符串,即使我的请求可以在PostMan中使用.

I'm trying to make a POST request with a GraphQL query, but it's returning the error Must provide query string, even though my request works in PostMan.

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

Here is how I have it running in PostMan:

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

And here is the code I'm running in my application:

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 请求传递的body属性被格式化为 Text ,就像我在PostMan请求的正文中指定的一样?

Any ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the fetch request is formatted as Text like I've specified in the PostMan request's body?

推荐答案

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

The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.

这应该适合您的情况:

const url = `http://localhost:3000/graphql`;
const query = `
  {
    users(name: "Thomas") { 
      firstName
      lastName 
    } 
  }
 `

return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

这是提交GraphQL变量的方法:

This is how to submit GraphQL variables:

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)
})

我在GitHub上创建了完整的示例.

I created a complete example on GitHub.

这篇关于使用Graphql查询的节点获取发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆