[英]GET Request 200 to json
我正在嘗試向 URL 發送獲取請求以接收一些 JSON,我得到的只是 HTTP/1.1 200 OK,當我嘗試 console.log 我的請求時,我在控制台中看不到任何內容,我正在嘗試將請求控制台記錄為 JSON。 我正在為該項目使用 Cloudflare 的牧馬人工具並在 javascript 中對其進行編碼這是我的代碼:
addEventListener('fetch', event => {
event.respondWith(handleRequest((event)))
})
/**
* Respond with hello worker text
* @param {Request} request
*/
async function handleRequest(request) {
return new Response('Hello worker!', {
headers: { 'content-type': 'application/json' },
})
}
const url =`URL`;
const res="";
fetch(`MYURL`)
.then((response) => {
return response.json();
})
.then((data) => {
dataRecieved=JSON.parse(data);
console.log(dataRecieved);
});
'Hello worker!'
不是有效的 JSON 所以JSON.parse(data)
將無法正常工作。 您應該使用這樣的代碼在響應中返回有效的 JSON:
return new Response('{"variants":["your-private-url/variants/1","your-private-url/variants/2"]}', {
headers: { 'content-type': 'application/json' },
status: 200
})
現在要獲得您在評論中提到的結果,您需要刪除事件偵聽器並以這種方式處理fetch
調用:
fetch('your-private-url')
.then((response) => {
return response.json();
})
.then((data) => {
// 'data' here contains the object returned by your request.
// So you can log the whole object received to see its content:
console.log('Received data:\n', data);
// And you can access the fields and log them:
data.variants.forEach(variant => {
console.log('Reveived variant: ', variant);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.