developer tip

ReferenceError : 가져 오기가 정의되지 않았습니다.

optionbox 2020. 9. 21. 07:37
반응형

ReferenceError : 가져 오기가 정의되지 않았습니다.


node.js에서 코드를 컴파일 할 때이 오류가 발생합니다. 어떻게 수정할 수 있습니까?

RefernceError : 가져 오기가 정의되지 않았습니다.

여기에 이미지 설명 입력

이것이 제가하고있는 기능이며 특정 영화 데이터베이스에서 정보를 복구하는 역할을합니다.

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

가져 오기 API는 노드에 구현되지 않습니다.

이를 위해 node-fetch 와 같은 외부 모듈을 사용해야합니다 .

다음과 같이 Node 애플리케이션에 설치하십시오.

npm i node-fetch --save

그런 다음 fetch API를 사용하는 파일의 맨 위에 아래 행을 넣으십시오.

const fetch = require("node-fetch");

전역 범위로 액세스 할 수 있어야하는 경우

global.fetch = require("node-fetch");

이것은 빠른 수정이며 프로덕션 코드에서 사용을 제거하십시오.


@lquixada 에서 크로스 페치사용할 수 있습니다.

플랫폼에 구애받지 않음 : 브라우저, 노드 또는 반응 네이티브

설치

npm install --save cross-fetch

용법

약속 :

import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';

fetch('//api.github.com/users/lquixada')
  .then(res => {
    if (res.status >= 400) {
      throw new Error("Bad response from server");
    }
    return res.json();
  })
  .then(user => {
    console.log(user);
  })
  .catch(err => {
    console.error(err);
  });

async / await 사용 :

import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';

(async () => {
  try {
    const res = await fetch('//api.github.com/users/lquixada');

    if (res.status >= 400) {
      throw new Error("Bad response from server");
    }

    const user = await res.json();

    console.log(user);
  } catch (err) {
    console.error(err);
  }
})();

아직 포함하지 않기 때문에 프로젝트에 isomorphic-fetch모듈 을 사용해야합니다 . 이 문제를 해결하려면 아래 명령을 실행하십시오.NodeNodeFetch API

npm install --save isomorphic-fetch es6-promise

설치 후 프로젝트에서 아래 코드를 사용하십시오.

import "isomorphic-fetch"

이 답변이 도움이 되었기를 바랍니다.


가장 좋은 것은 가져 오기를위한 Axios 라이브러리입니다. 사용 npm i --save axiosinstallng 및 사용 가져처럼, 대신에 단지 쓰기 Axios의에서 응답을 한 후 가져 오기 및 다음 () .


node-js 에서 typescript사용 하고 오류가 발생하는 사람들ReferenceError: fetch is not defined

npm install 이 패키지 :

    "amazon-cognito-identity-js": "3.0.11"
    "node-fetch": "^2.3.0"

그런 다음 다음을 포함합니다.

import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
    fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');

참고 URL : https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined

반응형