带有查询字符串参数的 node.js http“get”请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16903476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:42:44  来源:igfitidea点击:

node.js http 'get' request with query string parameters

node.jshttpquery-string

提问by djechlin

I have a Node.js application that is an http client (at the moment). So I'm doing:

我有一个 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);
});

This seems like a good enough way to accomplish this. However I'm somewhat miffed that I had to do the url + querystep. This should be encapsulated by a common library, but I don't see this existing in node's httplibrary yet and I'm not sure what standard npm package might accomplish it. Is there a reasonably widely used way that's better?

这似乎是完成此任务的足够好方法。但是,我对必须执行此url + query步骤感到有些恼火。这应该由一个公共库封装,但我还没有在 node 的http库中看到它存在,我不确定什么标准的 npm 包可以完成它。是否有一种合理广泛使用的更好的方法?

url.formatmethod saves the work of building own URL. But ideally the request will be higher level than this also.

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

回答by Daniel

Check out the requestmodule.

查看请求模块。

It's more full featured than node's built-in http client.

它比 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);
});

回答by Justin Meiners

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

不需要第 3 方库。使用 nodejs url 模块构建带有查询参数的 URL:

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.pathwill include the query parameters.

然后使用格式化的 url 发出请求。requestUrl.path将包括查询参数。

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

回答by Abdennour TOUMI

If you don't want use external package , Just add the following function in your utilities :

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

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

Then , in createServercall back , add attribute paramsto requestobject :

然后,在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"

})

回答by AllJs

I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ?at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.

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

Below, is a simple API Endpoint that calls the Open Weather APIand passes APPID, latand lonas query parameters and return weather data as a JSONobject. Hope this helps.

下面是一个简单的API端点调用开放API天气并通过APPIDlatlon作为查询参数和返回的天气数据作为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.
        }
    })
})  

Or if you want to use the querystringmodule, make the following changes

或者如果要使用该querystring模块,请进行以下更改

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

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

回答by AmiNadimi

If you ever need to send GETrequest to an IPas well as a Domain(Other answers did not mention you can specify a portvariable), you can make use of this function:

如果您需要向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);
    });
}

Don't miss requiring modules at the top of your file:

不要错过文件顶部的 require 模块:

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

Also bare in mind that you may use httpsmodule for communicating over secured network.

还要记住,您可以使用https模块通过安全网络进行通信。