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


84

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을 구축하는 작업을 저장합니다. 그러나 이상적으로 요청은 이것보다 더 높은 수준이 될 것입니다.



답변:


158

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

노드의 내장 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);
});

일반적인 propertiesObject는 어떻게 보일까요? 이 작업을 할 수 없습니다
— user264230 2014-10-05

3
qs는 쿼리 문자열 키입니다. 따라서 쿼리 문자열에서 원하는 필드. {field1 : 'test1', field2 : 'test2'}
— Daniel

누구나 Nodejs 코어 http 모듈로 이것을 수행하는 방법을 알고 있습니까?
— Alexander Mills

1
@AlexanderMills가 내 대답을 봅니다. 타사 라이브러리는 필요하지 않습니다.
— Justin Meiners

9
요청 모듈은 이제 오래되어 더 이상 사용되지 않습니다.
— AmiNadimi

19

타사 라이브러리가 필요하지 않습니다. nodejs url 모듈 을 사용하여 쿼리 매개 변수가있는 URL을 작성하십시오.

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

그런 다음 형식화 된 URL로 요청하십시오. requestUrl.path검색어 매개 변수가 포함됩니다.

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

내장을 사용하는 기존 코드를 사용하고 싶기 때문에이 솔루션을 시도하고 사용할 것입니다 https. 그러나 OP는 쿼리로 URL 문자열을 구성하기 위해 더 높은 수준의 추상화 및 / 또는 라이브러리를 요청했기 때문에 대답은 개인적으로 더 유효
— 스콧 앤더슨

3
@ScottAnderson 내가 받아 들인 대답이 아니라면 괜찮습니다. 사람들이 필요한 작업을 수행하도록 돕고 싶을뿐입니다. 도움이 될 수있어서 다행입니다.
— Justin Meiners

6

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

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"

})

2
OP의 질문은 http 서버가 아닌 http 클라이언트에 관한 것입니다. 이 답변은 http 요청에 대한 쿼리 문자열을 인코딩하는 것이 아니라 http 서버에서 쿼리 문자열을 구문 분석하는 것과 관련이 있습니다.
— Stephen Schaub

이것은 질문이 묻는 것과 반대이며, 직접 구문 분석을 시도하는 것보다 Node의 내장 querystring모듈을 사용 하는 것이 좋습니다.
— peterflynn

6

내 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) {...})

1

혹시 전송해야하는 경우 GET에 요청을 IP뿐만 아니라 Domain(다른 답변은 당신이 지정할 수 있습니다 언급하지 않았다 port변수)를 사용하면이 기능을 사용할 수있다 :

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

파일 상단에 필요한 모듈을 놓치지 마세요.

http = require("http");
url = require('url')

또한 https보안 네트워크를 통해 통신 하기 위해 모듈을 사용할 수 있습니다 .

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.