我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?

我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?


当前回答

如果您想避免表达,请使用以下示例:

var http = require('http');
const url = require('url');

function func111(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var q = url.parse(req.url, true);
  res.end("9999999>>> " + q.query['user_name']); 
}

http.createServer(func111).listen(3000); 

用法:

curl http://localhost:3000?user_name=user1

通过yl

其他回答

一个小型Node.js HTTP服务器监听端口9080,解析GET或POST数据并将其作为响应的一部分发送回客户端:

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

将其保存为parse.js,然后在控制台上输入“nodeparse.js”来运行它。

app.get('/user/:id', function(req, res) {
    res.send('user' + req.params.id);    
});

您可以使用这个,也可以尝试使用主体解析器来解析请求参数中的特殊元素。

考虑一下这个url->/api/endpoint/:id?名称=萨希尔这里id是param,其中as name是查询。您可以像这样在nodejs中获取此值

app.get('/api/endpoint/:id', (req, res) => {
  const name = req.query.name; // query
  const id = req.params.id //params
});

如果您需要向IP和域发送GET请求(其他答案没有提到您可以指定端口变量),您可以使用此函数:

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

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

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

还要记住,您可以使用https模块通过安全域和ssl进行通信。因此这两条线将改变:

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

对于Express.js,您需要执行req.params:

app.get('/user/:id', function(req, res) {
  res.send('user' + req.params.id);    
});