Development Tip

쿼리 문자열 매개 변수가있는 node.js http 'get'요청

yourdevel 2020. 11. 26. 19:57
반응형

쿼리 문자열 매개 변수가있는 node.js http 'get'요청


http 클라이언트 인 Node.js 애플리케이션이 있습니다 (현재). 그래서 나는하고있다 :

var query = require('querystring').stringify(propertiesObject);
http.get(url + query, function(res) {
   console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

이것은 이것을 달성하기에 충분한 방법 인 것 같습니다. 그러나 나는 내가 그 url + query단계를 해야만했다는 것에 다소 미안하다 . 이것은 공통 라이브러리에 의해 캡슐화되어야하지만 http아직 노드의 라이브러리에 존재하지 않으며 표준 npm 패키지가이를 수행 할 수 있는지 확실하지 않습니다. 합리적으로 널리 사용되는 더 나은 방법이 있습니까?

url.format 메소드는 자신의 URL을 구축하는 작업을 저장합니다. 그러나 이상적으로 요청은 이것보다 더 높은 수준이 될 것입니다.


요청 모듈을 확인하십시오 .

노드에 내장 된 http 클라이언트보다 더 많은 기능을 제공합니다.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

외부 패키지를 사용하지 않으려면 유틸리티에 다음 기능을 추가하십시오.

var params=function(req){
  let q=req.url.split('?'),result={};
  if(q.length>=2){
      q[1].split('&').forEach((item)=>{
           try {
             result[item.split('=')[0]]=item.split('=')[1];
           } catch (e) {
             result[item.split('=')[0]]='';
           }
      })
  }
  return result;
}

그런 다음 createServer콜백 params에서 request객체 에 속성 추가 합니다.

 http.createServer(function(req,res){
     req.params=params(req); // call the function above ;
      /**
       * http://mysite/add?name=Ahmed
       */
     console.log(req.params.name) ; // display : "Ahmed"

})

내 URL에 쿼리 문자열 매개 변수를 추가하는 방법에 어려움을 겪고 있습니다. ?URL 끝에 추가해야한다는 것을 깨달을 때까지 작동하도록 만들 수 없었습니다 . 그렇지 않으면 작동하지 않습니다. 이것은 디버깅 시간을 절약 할 수 있기 때문에 매우 중요 합니다 . 저를 믿으십시오 .

이하, 호출하는 간단한 API 엔드 포인트입니다 열기 날씨 API를 하고 통과 APPID, lat그리고 lonA와 쿼리 매개 변수 및 반환 기상 데이터와 같은 JSON객체. 도움이 되었기를 바랍니다.

//Load the request module
var request = require('request');

//Load the query String module
var querystring = require('querystring');

// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;

router.post('/getCurrentWeather', function (req, res) {
    var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
    var queryObject = {
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    }
    console.log(queryObject)
    request({
        url:urlOpenWeatherCurrent,
        qs: queryObject
    }, function (error, response, body) {
        if (error) {
            console.log('error:', error); // Print the error if one occurred

        } else if(response && body) {
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.json({'body': body}); // Print JSON response.
        }
    })
})  

또는 querystring모듈 을 사용 하려면 다음과 같이 변경하십시오.

var queryObject = querystring.stringify({
    APPID: OpenWeatherAppId.appId,
    lat: req.body.lat,
    lon: req.body.lon
});

request({
   url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

참고URL : https://stackoverflow.com/questions/16903476/node-js-http-get-request-with-query-string-parameters

반응형