이것은 약속을 사용하는 내 코드입니다.
var http = require("http");
function webFunc(req, res){
var p = getData();
p.then(function(data) {
// var jsonData = JSON.parse(data);
// console.log(JSON.parse(data))
res.send(JSON.parse(data));
}).catch(function(err) {
console.log(err);
})
}
function getData(){
var prom=new Promise (function(resolve,reject){
http.get(url,function(res) {
var data = "";
res.on("data", function(chunk) {
data += chunk;
resolve(data);
return;
})
res.on("error", function(error) {
console.log("Got error: " + error.message);
reject(error);
});
});
})
return prom;
}
이렇게 JSON.parse를 설정하지 않고 경로를 실행할 때
res.send(data);
이렇게 JSON.parse를 설정하면 실행할 때마다 절반의 데이터 또는 모든 데이터가 있습니다.
res.send(JSON.parse(data));
이 오류가 발생했습니다
[SyntaxError: Unexpected token u]
or this
[SyntaxError: Unexpected end of input]
데이터의 결과는 8 개의 정보 객체를 포함해야합니다.
console.log(data)
console.log("typeof data",typeof data)
i got this
{"days":{"location":{"id":11,"name":"city","resultinfo":{"info":[{"d":"2017-02-07","tt":15,"ss":"39"
typeof data string
이 문제를 어떻게 해결할 수 있습니까?
데이터를 너무 빨리 사용하고 있습니다. 다음 문서의http.get
예를 참조하십시오 .
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
try {
let parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.log(e.message);
}
});
end
이벤트가 아닌 이벤트 에 대한 데이터를 사용하려고합니다 data
. 첫 번째 이벤트 에서 프로젝트를 해결하는 경우 데이터의 일부만 처리합니다 data
.
따라서 (주 ***
라인) :
function getData() {
var prom = new Promise(function(resolve, reject) {
http.get(url, function(res) {
var data = "";
res.setEncoding('utf8'); // See note below
res.on("data", function(chunk) { // ***
data += chunk; // ***
}) // ***
res.on("end", function() { // ***
resolve(data); // ***
}); // ***
res.on("error", function(error) {
console.log("Got error: " + error.message);
reject(error);
});
});
})
return prom;
}
으로 라이언이 지적 , 당신은 필요
res.setEncoding('utf8');
데이터 청크를 버퍼가 아닌 문자열로 원하는 경우 위에 표시됩니다.
다시 편집 :
데이터의 결과는 다음과 같은 8 개의 정보 객체를 포함해야합니다.
인용 한 데이터는 JSON이 아닙니다. JSON에서 속성 이름은 큰 따옴표로 묶어야합니다. JSON이 되려면 다음과 같아야합니다.
{ "first-days": { "location": { "id": 11, "loc": "city", "info": { } } } }
나는 전혀 이해가되지 않는 귀하의 예를 일부 생략했지만 요점을 알았습니다. JSON.org에 대해 자세히 알아보십시오 .
후속 편집은 실제를 보여줍니다. 우리가 볼 수있는 것은 유효한 JSON처럼 보입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다