programing

노드에서 HTTP 요청을 통해 JSON 가져오기JS

yellowcard 2023. 3. 6. 20:57
반응형

노드에서 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.requestJSON이 아닌 문자열을 수신(데이터)하는 이유는 무엇입니까?

 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);

Node.js를 사용하여 JSON을 해석하는 방법

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

반응형