我正在尝试向 URL 发送获取请求以接收一些 JSON,我得到的只是 HTTP/1.1 200 OK,当我尝试 console.log 我的请求时,我在控制台中看不到任何内容,我正在尝试将请求作为 JSON 进行 console.log 。我正在为该项目使用 Cloudflare 的 wrangler 工具,并使用 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 work!'
不是有效的 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);
});
});
关于javascript - GET 请求 200 转 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61271570/