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

前端 未结 26 3478
庸人自扰
庸人自扰 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:20

    A small Node.js HTTP server listening on port 9080, parsing GET or POST data and sending it back to the client as part of the response is:

    var sys = require('sys'),
    url = require('url'),
    http = require('http'),
    qs = require('querystring');
    
    var server = http.createServer(
    
        function (request, response) {
    
            if (request.method == 'POST') {
                    var body = '';
                    request.on('data', function (data) {
                        body += data;
                    });
                    request.on('end',function() {
    
                        var POST =  qs.parse(body);
                        //console.log(POST);
                        response.writeHead( 200 );
                        response.write( JSON.stringify( POST ) );
                        response.end();
                    });
            }
            else if(request.method == 'GET') {
    
                var url_parts = url.parse(request.url,true);
                //console.log(url_parts.query);
                response.writeHead( 200 );
                response.write( JSON.stringify( url_parts.query ) );
                response.end();
            }
        }
    );
    
    server.listen(9080);
    

    Save it as parse.js, and run it on the console by entering "node parse.js".

提交回复
热议问题