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

前端 未结 5 1581
悲&欢浪女
悲&欢浪女 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:31

    If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

    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:

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

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

提交回复
热议问题