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

前端 未结 5 1582
悲&欢浪女
悲&欢浪女 2020-12-04 15:29

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

var query = require(\'querystring\').stringify(propertiesObject);
http.g         


        
5条回答
  •  囚心锁ツ
    2020-12-04 15:43

    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.

    Below, is a simple API Endpoint that calls the Open Weather API and passes APPID, lat and lon as query parameters and return weather data as a JSON object. Hope this helps.

    //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 querystring module, make the following changes

    var queryObject = querystring.stringify({
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    });
    
    request({
       url:urlOpenWeatherCurrent + queryObject
    }, function (error, response, body) {...})
    

提交回复
热议问题