How to call a GraphQL query/mutation from an Express server backend?

This is more likely to be what you're looking for:

const { createApolloFetch } = require('apollo-fetch');

const fetch = createApolloFetch({
    uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});


// Example # 01
fetch({
    query: '{ posts { title } }',
}).then(res => {
    console.log(res.data);
});


// Example # 02
// You can also easily pass variables for dynamic arguments
fetch({
    query: `
        query PostsForAuthor($id: Int!) {
            author(id: $id) {
                firstName
                posts {
                    title
                    votes
                }
            }
        }
    `,
    variables: { id: 1 },
}).then(res => {
    console.log(res.data);
});

Taken from this post, might be helpful to others as well: https://www.apollographql.com/blog/graphql/examples/4-simple-ways-to-call-a-graphql-api/


You can use graphql-request, it is a simple GraphQL client.

const { request } = require('graphql-request');

request('http://localhost:3333/graphql', `mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: '[email protected]', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

It also support CORS.

const { GraphQLClient } = require('graphql-request');

const endpoint = 'http://localhost:3333/graphql';
const client = new GraphQLClient(endpoint, {
  credentials: 'include',
  mode: 'cors'
});

client.request(`mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: '[email protected]', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

I use it to make E2E tests.