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 와 같은 외부 모듈을 사용해야합니다 .
다음과 같이 노드 애플리케이션에 설치하십시오.
npm i node-fetch --save
그런 다음 페치 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);
});
비동기 / 대기 :
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);
}
})();
답변
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');
답변
아직 포함되어 있지 않기 때문에 프로젝트에 isomorphic-fetch
모듈 을 사용해야합니다 . 이 문제를 해결하기 위해 아래 명령을 실행하십시오.Node
Node
Fetch API
npm install --save isomorphic-fetch es6-promise
설치 후 프로젝트에서 아래 코드를 사용하십시오.
import "isomorphic-fetch"
이 답변이 도움이 되길 바랍니다.
답변
가장 좋은 것은 페치 용 Axios 라이브러리입니다. 사용 npm i --save axios
installng 및 사용 가져처럼, 대신에 단지 쓰기 Axios의에서 응답을 한 후 가져 오기 및 다음 () .
답변
Node.js는 fetch () 메소드를 구현하지 않았지만이 환상적인 실행 환경의 외부 모듈 중 하나를 JavaScript에 사용할 수 있습니다.
위의 답변 중 하나에서 “node-fetch”가 인용되었으며 이는 좋은 선택입니다.
프로젝트 폴더 (.js 스크립트가있는 디렉토리)에서 다음 명령을 사용하여 해당 모듈을 설치하십시오.
npm i 노드 가져 오기-저장
그런 다음 Node.js로 실행할 스크립트에서 상수로 다음과 같이 사용하십시오.
const fetch = require ( “node-fetch”);
