88

我有一个 Node.js 应用程序,它是一个 http 客户端(目前)。所以我在做:

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一步。这应该由一个通用库封装,但我在 node 的http库中还没有看到它,我不确定哪个标准 npm 包可以完成它。有没有更好的合理广泛使用的方法?

url.format方法节省了构建自己的 URL 的工作。但理想情况下,请求也会比这更高。

4

5 回答 5

167

查看请求模块。

它比 node 的内置 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);
});
于 2013-06-03T19:01:24.013 回答
30

不需要第 3 方库。使用 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) => {
   // ...
})
于 2019-02-18T20:39:38.007 回答
7

如果您不想使用外部包,只需在实用程序中添加以下功能:

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回调中,将属性添加paramsrequest对象:

 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"

})
于 2016-07-19T00:59:46.393 回答
6

我一直在努力解决如何将查询字符串参数添加到我的 URL。直到我意识到我需要?在我的 URL 末尾添加,我才能让它工作,否则它不会工作。这非常重要,因为它可以为您节省数小时的调试时间,相信我:去过那里...做过

下面是一个简单的 API Endpoint,它调用Open Weather API并传递APPID,latlon作为查询参数并将天气数据作为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) {...})
于 2017-03-19T12:28:19.360 回答
2

如果您需要向a 和 a发送GET请求(其他答案未提及您可以指定变量),您可以使用此函数:IPDomainport

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模块通过安全网络进行通信。

于 2020-02-13T05:46:10.663 回答