将块连接到AEM Edge函数
我们的目标是生成动态Edge Delivery Services块,该块调用AEM Edge函数以从第三方API获取动态数据。
第三步是将您在🔗中构建的Edge Delivery Services块连接到开发Edge Delivery Services函数中构建的AEM Edge函数。 这是将两个项目联系在一起的步骤。 在两个不同的端口上并排运行两个本地开发服务器,并根据运行位置使块的JavaScript调用正确的服务器。
运行两个本地开发服务器
在Edge Delivery Services站点项目中:
$ aem up
此服务在http://localhost:3000上提供站点。
在AEM Edge Functions项目中,在第二个终端:
$ aio aem edge-functions serve
这为http://127.0.0.1:7676处的终结点提供服务。
接通获取调用
将以下内容添加到estimated-delivery.js中,并与开发Edge Delivery Services块中的基架一起使用。
为环境选择正确的URL
Edge Delivery Services块会根据其运行位置调用其他URL:
http://127.0.0.1:7676/api/frescopa/estimated-delivery/api/frescopa/estimated-delivery (相对)从浏览器报告的主机名中检测本地开发,并缓存结果,以便每个请求都不会重复检查:
// blocks/estimated-delivery/estimated-delivery.js
const API_PATH = '/api/frescopa/estimated-delivery';
const LOCAL_EDGE_FUNCTION_ORIGIN = 'http://127.0.0.1:7676';
let cachedApiUrl;
function isLocalDev() {
const { hostname } = window.location;
return hostname === 'localhost' || hostname === '127.0.0.1';
}
function getEstimatedDeliveryApiUrl() {
if (cachedApiUrl) return cachedApiUrl;
// Local: site (aem up) on :3000, Edge Function on :7676 — call it directly.
// Production: relative path, routed to Edge Function via CDN origin selector.
cachedApiUrl = isLocalDev()
? `${LOCAL_EDGE_FUNCTION_ORIGIN}${API_PATH}`
: API_PATH;
return cachedApiUrl;
}
这是Edge Delivery Services块中唯一特定于环境的逻辑。 其他所有操作(获取调用、响应处理、渲染)在这两个环境中的工作方式都相同,因为路径相同;只有源发生变化。
localhost:3000到127.0.0.1:7676),因此它取决于您在开发AEM Edge函数中添加到AEM Edge函数的CORS标头。 如果没有这些参数,浏览器将阻止响应,并且获取调用会引发一般网络错误。调用AEM Edge函数
// blocks/estimated-delivery/estimated-delivery.js
async function fetchEstimatedDelivery(sku, postcode, signal) {
const params = new URLSearchParams({ sku, postcode });
const response = await fetch(`${getEstimatedDeliveryApiUrl()}?${params.toString()}`, {
signal,
cache: 'no-store',
});
const body = await response.json().catch(() => ({}));
if (!response.ok) {
const apiMessage = body.message || body.error;
const err = new Error(apiMessage || 'Unable to check estimated delivery right now.');
err.code = body.code;
throw err;
}
return body;
}
err.code包含来自定义API协定 (MISSING_POSTCODE, UNKNOWN_SKU)的相同code字段,因此调用方可以在其上分支。 Edge Delivery Services块仅显示message。 cache: 'no-store'阻止浏览器缓存个性化响应。 CDN自己的缓存行为由cdn.yaml中的skipCache单独控制,在构建API终结点中涵盖。
连接提交处理程序
从开发Edge Delivery Services块中的表单标记后,将此内容添加到decorate()。 这是核心模式:取消任何正在运行的请求,显示加载,调用函数,并将结果路由到setState:
// blocks/estimated-delivery/estimated-delivery.js
form.addEventListener('submit', async (event) => {
event.preventDefault();
// ...extract and validate sku/postcode from the form, omitted here...
activeRequest?.abort();
const controller = new AbortController();
activeRequest = controller;
setState({ loading: true });
try {
const data = await fetchEstimatedDelivery(sku, postcode, controller.signal);
setState({ data });
} catch (err) {
if (err.name === 'AbortError') return;
setState({ error: formatError(err) });
}
});
setState封装renderResult(),该封装在加载、错误和成功标记之间切换。 通过formatError()引发错误,它将网络故障(AEM Edge函数不可访问,因此本地开发服务器未运行或尚未部署CDN路由)与AEM Edge函数有意返回的业务错误(例如未知SKU)区分开来。 完整处理程序还会在调用函数之前验证邮政编码客户端,并在请求执行时禁用提交按钮。 在estimated-delivery.js中查看完整的侦听器renderResult()和formatError()。
在本地测试整个循环
运行两个开发服务器后,打开您在http://localhost:3000/dev/branches/estimated-delivery上创作的页面,提交表单,并确认结果呈现为带有AEM Edge函数上游调用数据的状态色卡片。
然后验证其他两种状态:
-
提交时邮政编码字段为空。 Edge Delivery Services块应显示“需要邮政编码”而不进行网络调用,以确认客户端检查在
fetchEstimatedDelivery()之前运行。 -
停止
aio aem edge-functions serve并再次提交。 Edge Delivery Services块应显示本地网络故障提示,确认formatError()选取了本地开发分支。停止本地Edge函数后
打开浏览器控制台获取其中的任何内容。 如果请求意外失败,请首先检查它是CORS错误(在AEM Edge函数中修复)还是连接错误(AEM Edge函数的开发服务器未运行)。
后续步骤
在部署和验证中,您部署了这两个项目并确认同一流程不仅在本地有效,而且适用于您的开发站点。