에서 SPA - [6] 서버에서 데이터 검색
취득 방법 알아보기
JS에서 서버에서 데이터를 얻는 방법에는 여러 가지가 있습니다. 조금 조사한 것만으로
XMLHttpRequest : 구식의 방법으로 로우 레벨을 쓰는 느낌 fetch API : 비교적 새로운. Chrome에서 말하면 버전 42에서 보인다 Vue의 권장 사항은 무엇입니까?
공식 사이트에서는, 뭐, 뭐든지 좋지만
jQuery 그리고 어때? 라는 느낌을 쓰는 방법. superagent의 리타이어에 관한 기사로 2016년이므로 조금 체질지도.What Should I Use Then?
You are free to pick whatever you prefer (even just $.ajax), but as a default recommendation — particularly for new users — we suggest taking a look at Axios. It's currently one of the most popular HTTP client library -resource provides with a very similar API. In addition, it is universal, supports cancellation, and has TypeScript definitions.
각각 만져 보자.
커맨드 라인으로 빨리 하고 싶었기 때문에
axios 잡자XHR
미리
axios 패키지를 보관하십시오.const axios = require('axios');
let url = 'https://api-staging.megaport.com/v2/locations'
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
fetch
사전에
vue-resource 패키지 해 둔다. node 반환 값은 axios 개체var fetch = require("node-fetch");
let url = 'your-api-end-point-here';
fetch(url).then((response) => {
//console.log(response.status);
console.log(response);
}).catch(() => {
console.log("error caught!");
});
Hack Your Design!에 따르면, 여기
node-fetch를 사용하는 쓰기가 더 현대적이라는 것var fetch = require("node-fetch");
let url = 'your-api-end-point-here';
(async() => {
try {
const response = await fetch(url);
//console.log(response.status);
console.log(response);
} catch (e) {
console.log("error!")
}
})();
axios
const axios = require('axios');
let url = 'your-api-end-point-here'
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
fetch에서하지 않아도 Promise의 await에 상기를 붙이면 움직이고 그 쪽이 node의 준비가 필요 없기 때문에 간단했는지빠진 곳
Chrome DevTools는 console를 반환하지만,이 경우 어떻게 node에 액세스하는지 잘 모르겠습니다. 일단 fetch를 JSON으로 해 보자.fetch(url).then((response) => {
console.log(response.json()); // to JSON
}).catch(() => {
console.log("error!");
});
여기서
Promise의 반환 값을 Vue로 data 배열에 넣으려고하면 다음과 같이 발생합니다.[Vue warn]: Invalid prop: type check failed for prop "data". Expected Array, got Promise.
response의 내용을 확인하면 다음과 같이 되어 있고 Promise는 data 아래에 배열로 되어 있다. 점 표기법으로는 액세스 할 수 없습니다.
접근 방법은 stack overflow에서 발견되었다.
Promise를 사용한다.fetch(url)
.then(response => response.json())
.then(data => console.log(data)) // then で data にアクセス
.catch(error => console.error(error))
참고로 한 사이트
다음 번
서버의 가치를 얻었으므로 드디어
data에서 사용할 수 있습니다.시리즈
Reference
이 문제에 관하여(에서 SPA - [6] 서버에서 데이터 검색), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/narutaro/items/82f4d9635c398524431c텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)