入门从客户端连接到 GraphQL 服务器
从客户端连接到 GraphQL 服务器
网站可以从任何运行 JavaScript 的浏览器连接到 GraphQL 服务器。这包括:
- 客户端应用程序中的 Vanilla JS
- 使用框架(例如 Vue 或 React)
- 从 WordPress 编辑器块内部连接
连接服务器时,可以使用任意 GraphQL 客户端库,包括:
不过,连接 GraphQL 端点并不需要外部 JavaScript 库:如下所示,简单的 JavaScript 代码即可完成。
针对 GraphQL 端点执行 Query
以下 JavaScript 代码将带有变量的 Query 提交到 GraphQL 服务器,并将响应打印到控制台。
/**
* 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));
}
})();执行持久化 Query
执行持久化 Query 有以下几点不同:
- 无需提交 GraphQL Query
- 操作方式为
GET,而非POST - 变量和操作名称需添加到 URL 中
/**
* 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 标头
如果需要在操作中包含 nonce,请添加 X-WP-Nonce 标头。
输出您的 nonce:
<script>
const NONCE = '{ Print nonce value }' ;
</script>将其包含在 fetch 的标头中:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}