jjr*_*bit -1 javascript json fetch
fetch() 响应变量中的 JSON 数据存储在哪里?
我尝试通过检查标题来检查控制台中的属性,但我在那里看不到它。
fetch() 响应变量中的 JSON 数据存储在哪里?
最初,情况并非如此。当您从 获取响应时fetch,响应的正文尚未被读取(部分fetch内容)(它很可能正在浏览器的 ajax 模块中的某个缓冲区中等待,但您无法直接访问它)。text它正在等待您通过、json、arrayBuffer、blob、 或方法阅读formData。
就您而言,您可能正在使用json. 一旦您调用json,主体就会被读入内部缓冲区并进行解析,然后解析的结果将用于履行该json方法的承诺。因此,此时,它存储在json返回的 Promise 对象中,可以通过使用 Promise 来访问(而不是以任何其他方式)。
要访问响应的 JSON,您可以调用json并使用生成的 Promise:
fetch(/*...*/)
.then(response => {
if (!response.ok) {
throw new Error("HTTP status code " + response.status);
}
return response.json();
})
.then(data => {
// Use the parsed data here
})
.catch(error => { // If you return the chain, you can leave this off
// Handle/report the error here
});
Run Code Online (Sandbox Code Playgroud)
或在async函数内:
const response = await fetch(/*...*/);
if (!response.ok) {
throw new Error("HTTP status code " + response.status);
}
const data = await response.json();
// Use the parsed data here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |