2017-06-17 116 views
2

我试图使用GraphQL查询提出POST请求,但它返回错误Must provide query string,即使我的请求在PostMan中有效。使用Graphql查询节点提取发布请求

这是我如何让它在邮递员运行:

enter image description here

enter image description here

,这里是我的代码在我的应用我运行:

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请求的正文中指定的那样?

回答

6

本体预计会有一个query属性,其中包含查询字符串。另外还可以传递variable属性,以便为查询提交GraphQL变量。

这应该工作你的情况:

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变量:

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