2017-06-17 115 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