Node.js를 사용한JSON API 호출
사용자의 페이스북 프로필 사진을 앱에 로그인하려고 합니다.Facebook의 API에는 다음과 같이 기술되어 있습니다.http://graph.facebook.com/517267866/?fields=picture는 올바른 URL을 JSON 개체로 반환합니다.
제 코드에서 사진의 URL을 알고 싶습니다.다음을 시도했지만 여기에 없는 것이 있습니다.
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res) {
var fbResponse = JSON.parse(res)
console.log("Got response: " + fbResponse.picture);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
이 코드를 실행하면 다음과 같은 결과가 됩니다.
undefined:1
^
SyntaxError: Unexpected token o
at Object.parse (native)
그res의 의론http.get()콜백은 본문이 아니라 http입니다.ClientResponse 오브젝트본체를 조립해야 합니다.
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
기타 답변에 관한 문제:
- 안전하지 않다
JSON.parse - 응답코드조회없음
여기 있는 모든 답변은JSON.parse()위험한 방법으로.모든 콜은 항상 다음 주소로 전송해야 합니다.JSON.parse()에 있어서try/catch특히 여기서와 같이 외부 소스로부터의 JSON을 해석할 때 차단합니다.
사용할 수 있습니다.request다른 답변에서는 언급되지 않은 JSON을 자동으로 해석할 수 있습니다.를 사용하여 이미 답변이 있습니다.request모듈을 사용하지만JSON.parse()JSON을 수동으로 해석하려면 - 항상 내부에서 실행해야 합니다.try {} catch {}잘못된 JSON 오류를 처리하기 위해 차단합니다. 그렇지 않으면 전체 앱이 크래시됩니다.그리고 잘못된 JSON이 발생합니다. 절 믿으세요.
가 사용하는 기타 답변http사용하다JSON.parse()응용 프로그램을 손상시킬 수 있는 예외를 확인하지 않습니다.
아래에서는 안전하게 처리할 수 있는 몇 가지 방법을 보여 드리겠습니다.
모든 예에서 공개 GitHub API를 사용하므로 누구나 안전하게 코드를 사용해 볼 수 있습니다.
의 예request
다음은 다음 예시를 제시하겠습니다.requestJSON을 자동으로 해석합니다.
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
의 예http그리고.try/catch
이 방법에서는https- 변경만 하면 됩니다.https로.httpHTTP 접속이 필요한 경우:
'use strict';
var https = require('https');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var data = JSON.parse(json);
// data is available here:
console.log(data.html_url);
} catch (e) {
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
의 예http그리고.tryjson
이 예는 위와 비슷하지만 모듈을 사용하고 있습니다.(이해:저는 그 모듈의 저자입니다.)
'use strict';
var https = require('https');
var tryjson = require('tryjson');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
var data = tryjson.parse(json);
console.log(data ? data.html_url : 'Error parsing JSON!');
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
요약
가 사용하는 예request가장 간단합니다.그러나 어떤 이유로 사용하지 않으려면 항상 응답 코드를 확인하고 JSON을 안전하게 해석해야 합니다.
이와 같은 단순한 HTTP 요청은 모듈을 사용하는 것이 좋다고 생각합니다.npm과 함께 설치해야 합니다.npm install request코드에는 다음과 같은 것이 있습니다.
const request = require('request')
,url = 'http://graph.facebook.com/517267866/?fields=picture'
request(url, (error, response, body)=> {
if (!error && response.statusCode === 200) {
const fbResponse = JSON.parse(body)
console.log("Got a response: ", fbResponse.picture)
} else {
console.log("Got an error: ", error, ", status code: ", response.statusCode)
}
})
매우 사용하기 쉬운 get-json을 사용하고 있습니다.
$ npm install get-json --save
수입품get-json
var getJSON = require('get-json')
하기 위해서GET다음과 같은 작업을 수행합니다.
getJSON('http://api.listenparadise.org', function(error, response){
console.log(response);
})
또 다른 해결책은 사용자 악리에 대한 것입니다.
npm install axios
코드는 다음과 같습니다.
const url = `${this.env.someMicroservice.address}/v1/my-end-point`;
const { data } = await axios.get<MyInterface>(url, {
auth: {
username: this.env.auth.user,
password: this.env.auth.pass
}
});
return data;
Unirst Library는 이것을 매우 단순하게 합니다.사용하고 싶은 경우는, 를 인스톨 할 필요가 있습니다.unirest packagenpm then could could could could 그러면 코드는 다음과 같습니다.
unirest.get("http://graph.facebook.com/517267866/?fields=picture")
.send()
.end(response=> {
if (response.ok) {
console.log("Got a response: ", response.body.picture)
} else {
console.log("Got an error: ", response.error)
}
})
언급URL : https://stackoverflow.com/questions/11826384/calling-a-json-api-with-node-js
'programing' 카테고리의 다른 글
| 어떤 JSON 콘텐츠유형을 사용할까요? (0) | 2023.03.22 |
|---|---|
| react.display의 하위 구성요소를 재귀적으로 렌더링하는 방법 (0) | 2023.03.14 |
| 스프링 MVC @RestController 및 리다이렉트 (0) | 2023.03.14 |
| React.js는 어레이를 통해 루프를 생성합니다. (0) | 2023.03.14 |
| 워드프레스:사용자용 새 사용자 이름 필드 만들기 (0) | 2023.03.14 |