将请求发布到graphql服务器没有响应

时间:2019-02-26 04:53:42

标签: node.js json http graphql

我试图向我在localhost:4000上运行的graphql服务器发出POST请求。为了吸引用户,我使用了

getUsers(){
    var query = `{users(id:""){username}}`
   fetch('http://localhost:4000/graphql', {
     method:'POST',
     headers: {
       'Content-Type' :'application/json',
       'Accept': 'application/json',
     },
     body: JSON.stringify({
       query,
     })
   })
   .then(res => res.json())
   .then(res => console.log('data returned', res))

这不起作用,所以我发出了卷曲请求,以查看出了什么问题,

curl -X POST http://localhost:4000/graphql -H "Content-Type: application/json "-d "{"query": "{users(id:""){username}}"

运行此命令后,我会不断得到

Unexpected token q in JSON at position 

首先在Google上查找此问题后,我发现了一个我认为可能可以提供帮助的教程。学习完本教程后,我将代码更改为

  getUsers(){
    var query = `{users(id:""){username}}`
   fetch('http://localhost:4000/graphql', {
     method:'POST',
     headers: {
       'Content-Type' :'application/json',
       'Accept': 'application/json',
     },
     body: JSON.stringify({
       query,
     })
   })
   //.then(r => r.json())
   .then(res => res.text())
   .then(text => console.log('data returned', text))

仍然没有记录任何内容。 所以我最后一弯尝试解决这个问题

curl -X POST http://localhost:4000/graph0ql -d "{"query": "{users(id:""){username}}"

一直返回的

{"errors":[{"message":"Must provide query string."}]}

现在我被困住了,我不知道接下来该怎么做。 我检查了查询字符串,它在graphiql中给了我预期的响应,并且URL也正确。我的前端服务器(我是从中发出请求的)正在localhost:4200上运行

2 个答案:

答案 0 :(得分:0)

好吧,我感觉很傻。我没有正确调用函数。剩下的就是实际使用数据了

答案 1 :(得分:-1)

问题在于您如何传递查询对象。尝试将其更新为以下内容:

getUsers(){
  var query = `query getUsers { users(id:"") { username } }`
  fetch('http://localhost:4000/graphql', {
    method:'POST',
    headers: {
      'Content-Type' :'application/json',
      'Accept': 'application/json',
    },
    body: JSON.stringify({
      query: query,
    })
  })
  //.then(r => r.json())
  .then(res => res.text())
  .then(text => console.log('data returned', text))
}
相关问题