Ask Your Question
3

How can I allow GraphQL access from other origins using CORS settings?

asked 2023-03-07 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-02-06 04:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-07 11:00:00 +0000

Seen: 7 times

Last updated: Feb 06 '23