Ich habe mehrere Artikel darüber gelesen, aber keiner von ihnen funktioniert für mich.Wie man Graphql mit CORS laufen lässt
https://github.com/graphql/express-graphql/issues/14
Hier ist mein Express.js 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,
}))
Wenn ich es auf diese Weise tun, die Pre-Flight-OPTIONS erfolgreich ist, aber die tatsächliche POST-Anforderung fehlschlägt.
Ich verwende diese Funktion, um eine Anfrage an den lokalen graphql-Server zu stellen.
function postFn(url, payload) {
return $.ajax({
method: 'POST',
url: url,
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
data: payload
});
}
ist der Front-End-Code, um die POST-Anforderung auslösen:
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)
Die Fehlermeldung lautet:
Nein "Access-Control-Allow-Origin-Header auf vorhanden ist die angeforderte Ressource