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
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With