How to get GET (query string) variables in Express.js on Node.js?

前端 未结 26 3490
庸人自扰
庸人自扰 2020-11-21 23:53

Can we get the variables in the query string in Node.js just like we get them in $_GET in PHP?

I know that in Node.js we can get the URL in the request.

26条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:23

    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 domains and ssl. so these two lines would change:

    https = require("https");
    ...
    https.get(url.format(requestUrl), (resp) => { ......
    

提交回复
热议问题