GraphQL request over HTTP

Hi, in this post we are going to create a simple web application (client) that will require the data from the GraphQL.

Note: last GraphQL chapter was the HTTP Request and Response format

So, the first step is create our client, so inside the project create a folder called “client” here live the HTML, CSS, JS code that control the the web application:

Next create the html file called index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>GraphQL client</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="main.js"></script>
  </head>
  <body>
    <h1>Loading...</h1>

    <script src="app.js"></script>
  </body>
</html>

Then Create the app.js file where we are going to insert all the code that handle the HTTP request:

So, using the fetch() method we can ask for the data to our GraphQL server.

Remember that the request need to be in JSON type so using the JSON.stringify() we are converting the query object to JSON format.

const GRAPHQL_URL = "http://localhost:9000/";

async function fetchGreeting() {
  const response = await fetch(GRAPHQL_URL, {
    // HTTP Request
    method: "POST",
    headers: {
      "content-type": "application/json",
    },
    // To convert Javascript object to JSON
    body: JSON.stringify({
      query: `
        query {
            greeting
        }
        `,
    }),
  });

  // HTTP Response
  const { data } = await response.json();

  return data;
}

fetchGreeting().then(({ greeting }) => {
  const title = document.querySelector("h1");
  title.textContent = greeting;
});

Nice, now run the server in the terminal:

Then open your client in the browser:

Final repository code:

https://github.com/cristinarojas/completeGraphQL

Thanks

Cristina Rojas