引用错误:未定义抓取

2022-08-29 23:19:14

当我在node中编译代码时遇到此错误.js,我该如何修复它?

引用错误:未定义获取

enter image description here

这就是我正在做的功能,它负责从特定的电影数据库中恢复信息。

function getMovieTitles(substr){  
  pageNumber=1;
  let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNumber;
  fetch(url).then((resp) => resp.json()).then(function(data) {
    let movies = data.data;
    let totPages = data.total_pages;
    let sortArray = [];
    for(let i=0; i<movies.length;i++){
        sortArray.push(data.data[i].Title);
     }
    for(let i=2; i<=totPages; i++){
           let newPage = i;
           let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;

          fetch(url1).then(function(response) {
              var contentType = response.headers.get("content-type");
              if(contentType && contentType.indexOf("application/json") !== -1) {
                return response.json().then(function(json) {
                  //console.log(json); //uncomment this console.log to see the JSON data.

                 for(let i=0; i<json.data.length;i++){
                    sortArray.push(json.data[i].Title);
                 }

                 if(i==totPages)console.log(sortArray.sort());

                });
              } else {
                console.log("Oops, we haven't got JSON!");
              }
            });

        }
  })
  .catch(function(error) {
    console.log(error);
  });   
}

答案 1

获取 API 未在 Node 中实现。

为此,您需要使用外部模块,例如node-fetch

像这样将其安装在您的 Node 应用程序中

npm install node-fetch

然后将以下行放在使用回迁 API 的文件的顶部:

import fetch from "node-fetch";

答案 2

这是一个快速的脏修复,请尝试在生产代码中消除这种用法。

如果必须通过全局范围进行访问fetch

import fetch from 'node-fetch'
globalThis.fetch = fetch