Kiril
Kiril

Reputation: 1

GraphQL CORS No 'Access-Control-Allow-Origin' header

When trying to make a GraphQL request I get the following error.

I am running an express server on port 3002. I am also running express-graphql on the express server with the "/graphql" endpoint.

I am using the apollo-client from a react app.

I have tried the following in my express code

app.use(cors())

However I am still getting the same error on the client

How do I resolve this CORS issue?

Upvotes: 0

Views: 18644

Answers (2)

Llewellyn Collins
Llewellyn Collins

Reputation: 2341

Make sure app.use(cors()) comes before you use graphQL.

Express code

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 ) );

Upvotes: 4

Amanpreet
Amanpreet

Reputation: 249

In your ExpressJS app on node.js, do the following with your routes:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

Upvotes: 2

Related Questions