简体   繁体   English

Express API 只返回对象的第一个键值对

[英]Express API only returns first key value pair of object

I'm fetching nested object data.我正在获取嵌套对象数据。 I can get that object data on console but when I try to get that data like return res.json(imageObject) I only get first key value pair of that object.我可以在控制台上获取该对象数据,但是当我尝试获取像return res.json(imageObject)这样的数据时,我只能得到该对象的第一个键值对。 This is the error to the console.这是控制台的错误。 UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client . UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Console data is like this { bigImage: 'https://url.com' }控制台数据是这样的{ bigImage: 'https://url.com' }

 router.get("/", async(req, res) => { //...fetch data if (mediaData.type === "type1") { let allData = await mediaData.media; allData.map(async(Data) => { if (Data.imageType === "big") { let bigImage = await Data.url; let imageObject = { bigImage }; console.log(imageObject); return res.json(imageObject); } }); } });

You are using res inside a .map , which will trigger it once for every item in the array you're iterating.您在.map中使用res ,它将为您正在迭代的数组中的每个项目触发一次。

You can't do that.你不能那样做。 You can only use res once for each req , because you're replying to the browser.您只能对每个req使用res一次,因为您正在回复浏览器。 If you use it more than once, you get this error, which means it's already been used and you have already replied.如果你多次使用它,你会得到这个错误,这意味着它已经被使用过并且你已经回复了。

Solution : use res once, not inside a map .解决方案:使用res一次,而不是在map

Also, .map is useless here, because you're not interested in the result it produces.此外, .map在这里没用,因为您对它产生的结果不感兴趣。 You should use forEach or even better, a for loop (which is breakable on condition).您应该使用forEach甚至更好的for循环(在条件下可破坏)。

You should use for..of .你应该使用for..of

It will stop the execution of your function at the return statement它将在 return 语句处停止执行您的函数

router.get("/", async(req, res) => {
  //...fetch data
  if (mediaData.type === "type1") {
    let allData = await mediaData.media;

    let pendingResult = allData.filter(data => data.imageType === "big").map(async item => {
       let bigImage = await item.url;
       return { bigImage }
    });
    
    let result = await Promise.all(pendingResult);

    res.json(result);
  }
});

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

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