나는 단순히 http 요청을 https://www.swapi.co/api/people/?search=Luke+
만들고 응답 데이터를 구문 분석하는 첫 번째 node.js 스크립트에서 작업하고 있습니다.
끝점은 다음과 같습니다.
var options = {
host: 'www.swapi.co',
path: `/api/people/?search=`+firstName+'+'+lastName
};
논리는 응답에서 데이터를 가져 와서 person
객체로 구문 분석하는 것입니다.
makeRequest(options, function( data, error) {
let person = data.results[0];
if (person) {
let height = person.height;
let response = person.name + " is " + height + " centimeters tall.";
callback(null, {"speech": response});
}
else {
callback(null, {"speech": "I'm not sure!"});
}
});
makerequest
기능 의 정의 는 다음과 같습니다.
function makeRequest(options, callback) {
var request = http.request(options,
function(response) {
var responseString = '';
response.on('data', function(data) {
responseString += data;
});
response.on('end', function() {
console.log('end: $$$' + responseString + '$$$');
var responseJSON = JSON.parse(responseString);
callback(responseJSON, null);
});
});
request.end();
}
스크립트를 실행할 때 JSON 구문 분석에 대한 오류가 발생했습니다.
Unexpected end of JSON input
at Object.parse (native)
at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
Postman을 사용하여 엔드 포인트를 테스트하고 응답으로 다음 JSON을 얻었습니다.
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://www.swapi.co/api/planets/1/",
"films": [
"https://www.swapi.co/api/films/2/",
"https://www.swapi.co/api/films/6/",
"https://www.swapi.co/api/films/3/",
"https://www.swapi.co/api/films/1/",
"https://www.swapi.co/api/films/7/"
],
"species": [
"https://www.swapi.co/api/species/1/"
],
"vehicles": [
"https://www.swapi.co/api/vehicles/14/",
"https://www.swapi.co/api/vehicles/30/"
],
"starships": [
"https://www.swapi.co/api/starships/12/",
"https://www.swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://www.swapi.co/api/people/1/"
}
]
}
그러나 코드를 디버깅 할 때 응답 데이터는 빈 문자열입니다. 그리고 그것은 JSON 오류를 설명합니다.
내 http 요청에 어떤 문제가 있습니까? 올바른 응답을받지 못하는 이유는 무엇입니까?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다