Erste SchritteVerbindung zum GraphQL-Server von einem Client
Verbindung zum GraphQL-Server von einem Client
Die Website kann sich von jedem Browser, der JavaScript ausführt, mit dem GraphQL-Server verbinden. Das umfasst:
- Vanilla JS in der clientseitigen Anwendung
- Die Verwendung eines Frameworks (wie Vue oder React)
- Aus einem WordPress-Editor-Block heraus
Du kannst jede GraphQL-Client-Bibliothek verwenden, um dich mit dem Server zu verbinden, darunter:
Es ist jedoch keine externe JavaScript-Bibliothek erforderlich, um sich mit dem GraphQL-Endpoint zu verbinden: Einfacher JavaScript-Code reicht bereits aus, wie unten gezeigt.
Queries gegen einen GraphQL-Endpoint ausführen
Dieser JavaScript-Code sendet eine Query mit Variablen an den GraphQL-Server und gibt die Antwort in der Konsole aus.
/**
* Replace here using either:
* - The single endpoint's URL
* - A custom endpoint's permalink
*/
const GRAPHQL_ENDPOINT = '{ YOUR_ENDPOINT_URL }';
(async function () {
const limit = 3;
const data = {
query: `
query GetPostsWithAuthor($limit: Int) {
posts(pagination: { limit: $limit }) {
id
title
author {
id
name
}
}
}
`,
variables: {
limit: `${ limit }`
},
};
const response = await fetch(
GRAPHQL_ENDPOINT,
{
method: 'post',
body: JSON.stringify(data),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Content-Length': data.length,
},
credentials: 'include',
}
);
/**
* Execute the query, and await the response
*/
const json = await response.json();
/**
* Check if the query produced errors, otherwise use the results
*/
if (json.errors) {
console.log(JSON.stringify(json.errors));
} else {
console.log(JSON.stringify(json.data));
}
})();Persistierte Queries ausführen
Die Ausführung einer persistierten Query hat einige Unterschiede:
- Es ist nicht notwendig, eine GraphQL-Query zu senden
- Die Operation ist
GET, nichtPOST - Variablen und Operationsname müssen zur URL hinzugefügt werden
/**
* Replace here using:
* - A persisted query's permalink
*/
const GRAPHQL_PERSISTED_QUERY_PERMALINK = '{ YOUR_PERSISTED_QUERY_PERMALINK }';
(async function () {
const limit = 3;
/**
* If needed, add variables in the URL
*/
const GRAPHQL_PERSISTED_QUERY = `${ GRAPHQL_PERSISTED_QUERY_PERMALINK }?limit=${ limit }`;
const response = await fetch(
GRAPHQL_PERSISTED_QUERY,
{
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Content-Length': data.length,
},
credentials: 'include',
}
);
const json = await response.json();
if (json.errors) {
console.log(JSON.stringify(json.errors));
} else {
console.log(JSON.stringify(json.data));
}
})();Nonce-Header senden
Wenn du eine Operation ausführen musst, die einen Nonce enthält, füge den X-WP-Nonce-Header hinzu.
Gib deinen Nonce aus:
<script>
const NONCE = '{ Print nonce value }' ;
</script>Füge ihn in die Header von fetch ein:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}