[SOLVED] CORS Errors with Apollo on Meteor 1.4x

I’m just putting this here for reference purposes. I’m using Apollo in Meteor 1.4x, and I just got my first mutation working in client code. One of the things I had to figure out was the CORS (Cross Origin Request) error.

My Meteor app includes Apollo running on an Express server at http://localhost:8080/graphql. When I sent an Apollo query to that server from localhost:3000, I was getting a CORS error. This has now been fixed.

Here’s the entire Apollo setup from my server/main.js:

import express from 'express';
import Schema from '/imports/api/schema';
import Mocks from '/imports/api/mocks';
import Resolvers from '/imports/api/resolvers';
import Connectors from '/imports/api/db-connectors';
import { apolloExpress, graphiqlExpress } from 'apollo-server';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import  cors  from 'cors';
import bodyParser from 'body-parser';

const executableSchema = makeExecutableSchema({
    typeDefs: Schema,
    resolvers: Resolvers,
    connectors: Connectors,
    logger: console,
});

const GRAPHQL_PORT = 8080;
const graphQLServer = express();

//FIXES CORS ERROR
var whitelist = [
    'http://localhost:3000',
];
var corsOptions = {
    origin: function(origin, callback){
        var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
        callback(null, originIsWhitelisted);
    },
    credentials: true
};
graphQLServer.use(cors(corsOptions));

// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
    schema: executableSchema,
    context: {}, //at least(!) an empty object
}));

graphQLServer.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
}));

graphQLServer.listen(GRAPHQL_PORT, () => console.log(
    `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));

When Meteor 1.5 comes out, all of this may be taken care of automatically. In the meantime, this post may save somebody some time. :slight_smile:

8 Likes

cool…thanks very much.

You’re very welcome. I’m working on the server side for Apollo pubsub now. If you get it working before I do, please let me know. :slight_smile:

In case you’re using createApolloServer
example below without corsOptions (enables cors access to all domains)

import { createApolloServer } from 'meteor/apollo';
import cors from 'cors';

import schema from '../../api/schema';

createApolloServer({
  schema,
}, {
  configServer: graphQLServer => graphQLServer.use(cors()),
});

7 Likes

is turning off cors safe in production?

If your app needs CORS, it needs it in production as well as in development.