Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To allow GraphQL access from other origins using CORS settings, you can add the following code snippet to your server-side code:

const express = require('express');
const cors = require('cors');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use(cors());

app.use('/graphql', graphqlHTTP({
  schema: schema, // Your GraphQL schema
  graphiql: true, // Enable GraphiQL GUI for testing queries
}));

app.listen(4000, () => console.log('Server running on port 4000'));

Here, we are using the "cors" middleware to set the Access-Control-Allow-Origin header to "*" which allows any origin to access our GraphQL server. You can also set a specific origin by passing the origin string to the cors() function.