当我在node.js中编译我的代码时,我有这个错误,我该如何修复它?

RefernceError:没有定义fetch

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

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);
  });   
}

当前回答

只要把你的app.js文件扩展为app.mjs,问题就会解决!!:)

其他回答

实际上有很多不同的库可以在浏览器中获取。

我所知道的主要问题有:

node-fetch cross-fetch whatwg-fetch isomorphic-fetch

我目前使用节点获取,它工作得很好,但我真的不知道哪一个是“最好的”。(尽管我链接的openbase.com页面提供了一些使用情况的元数据。Github星,npm下载],这可以帮助)

如果您使用的是18之前的Node版本,那么获取API并不是开箱即用的,您需要使用外部模块来实现,比如节点获取。

像这样在Node应用程序中安装它

npm install node-fetch

然后把下面的一行放在你正在使用fetch API的文件的顶部:

import fetch from "node-fetch";

这是相关的github问题 此错误与2.0.0版本有关,您可以通过简单地升级到2.1.0版本来解决它。 你可以跑 NPM I graphql-request@2.1.0-next.1

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

如果fetch必须在全局范围内访问

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

在HackerRank中,有些库默认安装,有些没有安装。

因为它运行的是Node.js,所以默认情况下不会安装获取API。

最好的方法是检查是否安装了库。

在练习的顶部,有以下几点:

const https = require('https');

请试着把这个也添加到顶部:

const axios = require('axios');

然后运行代码。

如果存在编译错误,则不可用,否则可以使用axios,这是获取的一个很好的替代方法

要使用它,你可以:

function getMovieTitles(substr){
  axios.get(url)
    .then(function(response){
      console.log(response.data);
    })
}

或者利用async/await

async function getMovieTitles(substr){
  let response = await axios.get(url)
  console.log(response.data);
}