Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Graphql run with CORS

Tags:

graphql

I've read several articles about this, but none of them work for me.

https://github.com/graphql/express-graphql/issues/14

Here is my expressjs code:

app.use("/graphql", function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});


// apply graphql middleware
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: rootResolver,
  graphiql: true,
}))

If I do it this way, the pre-flight OPTIONS is successful, but the actual POST request fails.

I am using this function to make request to local graphql server.

function postFn(url, payload) {
  return $.ajax({
    method: 'POST',
    url: url,
    contentType: 'application/json',
    xhrFields: {
      withCredentials: true
    },
    data: payload
  });
}

Here is the front-end code to trigger the POST request:

  let query = `
    query myqury($offset: Int, $limit: Int) {
      clients(limit:$limit , offset:$offset ) {
        docs{
          _id
          full_name
        }
        total
        limit
        offset
      }
    }
  `
  var variables = {
    offset: offset,
    limit: limit
  }
  let payload = {
    query: query,
    variables: variables
  }
  return request.post(graphQlEndpoint, payload)

The error message is:

No 'Access-Control-Allow-Origin' header is present on the requested resource

like image 379
Nicolas S.Xu Avatar asked Jun 20 '17 18:06

Nicolas S.Xu


1 Answers

I had the same issue as you. Using the graphQL on an express server.

Try using express cors

Use it in your express code like this

const express = require( `express` );
const graphqlHTTP = require( `express-graphql` );
const cors = require( `cors` );
const app = express();

app.use( cors() );
app.use(
    `/graphql`,
    graphqlHTTP( {
        schema: schema, // point to your schema 
        rootValue: rootResolver, // point to your resolver 
        graphiql: true
    } )
);

Fetch example based on GraphQL Documentation

fetch( url, {
    method : `post`,
    headers: {
        'Content-Type': `application/json`,
        'Accept'      : `application/json`
    },
    body: JSON.stringify( {
        query: `
        {
            person {
                name
            }
        }`
    } )
} )
.then( response => response.json() )
.then( response => console.log( response ) );
like image 133
Llewellyn Collins Avatar answered Oct 15 '22 19:10

Llewellyn Collins