Fetch + GraphQL
GraphQL APIs accept POST requests with a JSON body containing a query string and optional variables.
GraphQL APIs accept POST requests with a JSON body containing a query string and optional variables.
async function gql(query, variables = {}) {
const res = await fetch("/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query, variables }),
});
const { data, errors } = await res.json();
if (errors) throw new Error(errors[0].message);
return data;
}
const { user } = await gql(`query($id:ID!){user(id:$id){name email}}`, { id: "1" });
GraphQL always returns 200 OK — check the errors array in the response body, not the status code.
More in JavaScript