You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fetch('https://github.com/graphql',{method: 'POST',headers: {"Content-Type": "application/json","Authorization": "Bearer <Token>",},body: JSON.stringify({// GraphQL, this query decides to get the first 6 discussions in the repo, responds with their title and URL.query: ` query { repository(owner: "ocoke", name: "Biscus") { discussions(first: 6) { nodes { title url } } } }`,}),}).then(res=>res.json()).then(res=>res.data)
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
您可以使用 JavaScript 的内置
fetchAPI 以简单的方式查询 GraphQL API,无需任何库或依赖项 。[desc_end]Fetch API
您可以使用 JavaScript 的内置
fetchAPI 以简单的方式查询 GraphQL API,无需任何库或依赖项 .首先,我们应该将 GraphQL API URL 放入
fetch()POST 方法中。例如,GitHub 的 GraphQL API URL 是
https://api.github.com/graphql,因此我们可以得到:请求 Headers
然后,我们应该设置请求标头。 GraphQL 要求请求的
Content-Type应为application/json。一些 API(如 GitHub)也需要携带令牌来请求。
请求 Body
与 REST API 不同的事情之一是 GraphQL 可以让开发人员决定应该响应什么样的数据。
正文应该是 JSON 格式,并且有一个名为
query的键,其中包含查询参数,我们使用JSON.stringify()将object转换为string,以便在fetch()中发出请求。好,现在我们已经通过
fetch()从 GraphQL API 获取数据。Beta Was this translation helpful? Give feedback.
All reactions