我对 openlibrary 的获取请求被捕获

问题描述 投票:0回答:1

我正在尝试向 openlibrary API 写入获取请求,但到目前为止它一直被捕获并返回 console.log 错误。我认为我输入的网址不正确,但我不确定。我尝试过用几种方式重新表述它,但到目前为止还没有奏效。我对编写 fetch 还比较陌生。

正在搜索 ISBN。 它是 。当我引用它来创建文本时,我还想验证我是否具有正确格式的电子书可用性数据属性。


var fetchRequest = function() {

          var isbn = '0553283685';
          //var searchURL = `https://openlibrary.org/api/books?bibkeys=ISBN:" + ISBN${isbn}&format=json&jscmd=data`; 

          var searchURL = "https://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&format=json&jscmd=data";
          
          fetch(searchURL)
          .then(function(response) {
              return response.json();
          })
          .then(function(response2) {
              return response2.items.map(function(book) {
                createBookList(book)
              })   

            })  
          .catch( function()  {
              console.log(`There was an error with the fetch request`);       
          }); 
      }       

不确定电子书可用性数据属性是点 url 还是下划线 url。或者其他什么。

var ebookAvailable = book.ebooks.availability.pdf.url

var ebookAvailable = book.ebooks.availability.pdf_url
javascript fetch-api
1个回答
0
投票

首先,打印错误:

// omit stuff...
          .catch( function(e)  {
              console.log(e)
              console.log(`There was an error with the fetch request`);       
          }); 
// omit stuff...

从错误

TypeError: Cannot read properties of undefined (reading 'map')
,我们可以知道响应类型是意外的。让我们检查一下:

// omit stuff...
          .then(function(response2) {
              console.log(JSON.stringify(response2))
              return response2.items.map(function(book) {
// omit stuff...

这是什么?一本字典。

{"ISBN:0553283685":{"url":"https://openlibrary.org/books/OL16710277M/Hypérion","key":"/books/OL16710277M","title":"Hypérion"}, ...}'

所以,事实证明你不能这样解析结果。要迭代字典,请使用 this:

(function() {

          var isbn = '0553283685';
          //var searchURL = `https://openlibrary.org/api/books?bibkeys=ISBN:" + ISBN${isbn}&format=json&jscmd=data`; 

          var searchURL = "https://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&format=json&jscmd=data";
          
          fetch(searchURL)
          .then(function(response) {
              return response.json();
          })
          .then(function(response2) {
              books = []
              for (const [key, value] of Object.entries(response2)) {
                  books.append(createBookList(book))
              }
              return books

            })
© www.soinside.com 2019 - 2024. All rights reserved.