我正在尝试编写cloudflare工作者脚本来应对挑战。我需要在脚本中获取存储在urls
var中的给定URL,这将提供两个URL的json数组。我需要对数组中的其中一个网址发出提取请求,在这里我写的代码
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond with urls
* @param {Request} request
*/
async function handleRequest(request) {
var urls= await fetch('https://cfw-takehome.developers.workers.dev/api/variants')
.then(function(res){
return res;
})
var first=await urls.variants[0];
return first;
}
这是urls
变量包含的JSON
{"variants":["https://cfw-takehome.developers.workers.dev/variants/1","https://cfw-takehome.developers.workers.dev/variants/2"]}
但是我看到当我尝试访问数组中的第一个对象时,由于出现此错误,它是未定义的
Uncaught (in response) TypeError: Cannot read property '0' of undefined
[请帮助我找到原因,并提出解决方案。我想我在这里无法理解有关异步Javascript的一些概念。
您在这里犯了一些错误:
第一个是您需要返回res.json()
而不是仅返回res
,因为从fetch
返回的响应对象不是实际响应,需要序列化。
第二个是您不需要另一个await
,因为它将创建不必要的承诺。
所以这是正确的功能代码:
async function handleRequest() {
var urls = await fetch('https://cfw-takehome.developers.workers.dev/api/variants')
.then(res => res.json()) // res.json() instead just res
var first = urls.variants[0]; // await removed
return first;
}