2017-06-20 6 views
0

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

Antwort

0

Ich hatte das gleiche Problem beim Anrufen mit Vue-Client. Die einzige Möglichkeit, die ich beheben konnte, bestand darin, die Cross-Origin-Einschränkung für Testzwecke im Browser zu deaktivieren.

1

Bitte geben Sie unten Code in Ihre server.js Datei

const graphQLServer = express(); 
 
const corsOptions = { 
 
    origin(origin, callback) { 
 
     callback(null, true); 
 
    }, 
 
    credentials: true 
 
}; 
 
graphQLServer.use(cors(corsOptions)); 
 
var allowCrossDomain = function(req, res, next) { 
 
    res.header('Access-Control-Allow-Origin', '*'); 
 
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
 
    res.header('Access-Control-Allow-Headers', 'Content-Type,token'); 
 
    next(); 
 
} 
 
graphQLServer.use(allowCrossDomain);

Ich denke, das Ihr Problem lösen kann

Verwandte Themen