[英]Fields in response object from fetch method are undefined
我正在嘗試為帶回家的挑戰編寫一個 cloudflare worker 腳本。 我需要在我的腳本中獲取存儲在urls
var 中的給定 url ,這將給出一個包含兩個 url 的 json 數組。 我需要向數組中的一個 url 發出獲取請求,這里是我編寫的代碼
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;
}
這是 JSON urls
變量包含
{"variants":["https://cfw-takehome.developers.workers.dev/variants/1","https://cfw-takehome.developers.workers.dev/variants/2"]}
但是我看到當我嘗試訪問數組中的第一個 object 時,它是未定義的,因為我收到了這個錯誤
Uncaught (in response) TypeError: Cannot read property '0' of undefined
請幫我找出原因並提出解決方案。 我猜我在這里無法理解有關異步 Javascript 的一些概念。
你在這里犯了幾個錯誤:
第一個是您需要返回res.json()
而不僅僅是res
,因為從fetch
返回的響應 object 不是實際響應,需要序列化。
第二個是你不需要另一個await
,因為它會創建不必要的 promise。
所以這是正確的功能代碼:
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;
}
我已經在上面嘗試過,唯一需要的更改是返回 newResponse。
async function handleRequest() {
var urls = await fetch('https://cfw-takehome.developers.workers.dev/api/variants')
.then(response => response.json())
var first = urls.variants[0];
return new Response(first);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.