我為 Cloudflare 作業人員撰寫了這段代碼。
當在 Stripe 上創建新客戶時,會觸發一個 webhook 并將新客戶資料回傳到 [...].worker.dev/updateCustomers Cloudflare 作業人員將執行以下操作:
- 從客戶 JSON 物件中獲取名稱
- 在字串周圍創建一個沒有“”的版本
- 將新客戶添加到名為 customers[] 的陣列中
- 出于除錯原因,它將使用以下內容回復 Stripe:新客戶名稱、陣列中的所有客戶以及如果新客戶名稱包含在陣列中的結果
如果用戶打開到“https://[...]workers.dev/validate?licence=eee”的連接,如果名稱在客戶陣列中,它將回傳“合法”,如果不是,則回傳“失敗”。
通過 Stripe,當 webhook 被觸發時,我可以看到我的作業人員的以下回應:“收到的客戶:eee 其他客戶:demo,demo2,demo3,eee customers.includes(key): true”
這意味著新客戶已成功添加到陣列中,并且我的代碼能夠檢查客戶是否包含在陣列中。
但是當用戶試圖直接驗證他們的名字時,只有在開頭定義的陣列內容如“demo”、“demo2”得到肯定的回應。
誰能幫我解決這個問題?提前非常感謝。
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
customers = ["demo", "demo2","demo3"];
/**
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { pathname } = new URL(request.url);
if (pathname.startsWith("/api")) {
return new Response(JSON.stringify({ pathname }), {
headers: { "Content-Type": "application/json" },
});
}
if (pathname.startsWith("/validate")) {
let params = (new URL(request.url)).searchParams;
let key = params.get('licence');
console.log(key);
if(customers.includes(key)){
return new Response("legit");
}
else {
return new Response("failed");
}
}
if (pathname.startsWith("/updateCustomers")) {
let clonedBody = await request.clone().json();
let newCustomerName = JSON.stringify(clonedBody.data.object.name);
let newCustomerNameRaw = newCustomerName.substring(1, newCustomerName.length-1);
customers.push(newCustomerNameRaw);
return new Response("Customers recievedd: " newCustomerNameRaw " Other Customers: " customers.toString() " customers.includes(key): " customers.includes(newCustomerNameRaw) );
}
//fallback **strong text**not relevant
if (pathname.startsWith("/status")) {
const httpStatusCode = Number(pathname.split("/")[2]);
return Number.isInteger(httpStatusCode)
? fetch("https://http.cat/" httpStatusCode)
: new Response("That's not a valid HTTP status code.");
}
return fetch("https://welcome.developers.workers.dev");
}
uj5u.com熱心網友回復:
這是因為客戶“demo”、“demo2”和“demo3”作為代碼的一部分存盤在 webworker 中,所以無論何時呼叫它們都會出現。新客戶只是在代碼運行時臨時存盤在陣列中,但是一旦執行結束,客戶陣列內容就會被重置。如果您想在運行之間保留新客戶,您將需要使用某種后端來存盤客戶
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484852.html
標籤:javascript 数组 api 获取 API cloudflare 工作者
