简体   繁体   English

对象/json 在 fetch 中解构(然后)

[英]object/json destructuring inside fetch (then)

Don't know if this is good question since i'm beginner on JavaScript, but i want to use destructuring in fetch api getting error:不知道这是否是个好问题,因为我是 JavaScript 初学者,但我想在 fetch api 中使用解构获取错误:

Uncaught (in promise) TypeError: response is not iterable Uncaught (in promise) TypeError: response is not iterable

Where is the problem and what is good way to solve it?问题出在哪里,有什么好的解决方法? if possibly could you possibly write two version on with response.json and one without.如果可能的话,你可以用 response.json 写两个版本,一个不写。 thanks in advance.提前致谢。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <style> </style> </head> <body> <script> fetch("https://o", { method: "GET", headers: { "Content-type": "application/json", "X-API-Key": "***" } }) .then((response) => { // response.json().then(function(json) { const [b] = response //console.log(json) console.log(b) }); // }) </script> </body> </html>

Most probably response is not an array.很可能response不是数组。

If response has a property called b then I would try to destructure like the following:如果response有一个名为b的属性,那么我会尝试像下面这样解构:

const { b } = response;

Think about that as the following:考虑如下:

 const response = { b: { text: 'text', num: 123 } }; const { b } = response; console.log(b);

I hope this helps!我希望这有帮助!

if you want, you can also use fetches this way ;如果你愿意,你也可以使用这种方式获取;

fetch(url).then(response => response.json()
.then(data => //you can use whatever action you want to do there

The first then returns the response element to you, and you convert this response element to json format.然后第一个将响应元素返回给您,然后您将此响应元素转换为 json 格式。 In the second then you access the json format element and use it whatever you want to do.在第二个中,您访问 json 格式元素并使用它做任何您想做的事情。

If you want to know more about this subject, you can search the Promise object.如果你想了解更多关于这个主题的信息,你可以搜索 Promise 对象。

If you want, you can also use the async-await structure for api requests.如果需要,您还可以对 api 请求使用 async-await 结构。 It is shorter and more understandable.它更短,更容易理解。

async function getData(){
const response = await fetch(**your url**);
const data = await response.json();
return data; 
}

In this way, the use does the same with the fetch method.这样,use 和 fetch 方法一样。 Good Luck !祝你好运 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM