반응형
노드에서 HTTP 요청을 통해 JSON 가져오기JS
JSON 응답 모델을 다음에 나타냅니다.
exports.getUser = function(req, res, callback) {
User.find(req.body, function (err, data) {
if (err) {
res.json(err.errors);
} else {
res.json(data);
}
});
};
여기서 나는 그것을 얻습니다.http.request
JSON이 아닌 문자열을 수신(데이터)하는 이유는 무엇입니까?
var options = {
hostname: '127.0.0.1'
,port: app.get('port')
,path: '/users'
,method: 'GET'
,headers: { 'Content-Type': 'application/json' }
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log(data); // I can't parse it because, it's a string. why?
});
});
reqA.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
reqA.end();
JSON을 입수하려면 어떻게 해야 하나요?
http는 데이터를 문자열로 전송/수신합니다...원래 이렇습니다.문자열을 json으로 해석하려고 합니다.
var jsonObject = JSON.parse(data);
json:true를 사용 중임을 요청만 전달하고 헤더 및 해석은 무시하십시오.
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
우편물도 마찬가지입니다.
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
설정만json
할 수 있는 선택권true
본문에는 해석된 JSON이 포함됩니다.
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
언급URL : https://stackoverflow.com/questions/17811827/get-a-json-via-http-request-in-nodejs
반응형
'programing' 카테고리의 다른 글
스프링 데이터 - 값이 null인 경우 매개 변수 무시 (0) | 2023.03.06 |
---|---|
사용자 지정 위젯이 Visual Composer에 표시되지 않음 (0) | 2023.03.06 |
플레이 프레임워크 2.1 - 각도JS 라우팅 - 최적의 솔루션? (0) | 2023.03.06 |
상태 ''에서 '...'을(를) 확인할 수 없습니다. (0) | 2023.03.06 |
create-react-app에서 Import 바로가기/에일리어스를 만드는 방법 (0) | 2023.03.06 |