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

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


当前回答

一个小型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”来运行它。

其他回答

如果您需要向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中,这已经为您完成了,您可以简单地使用req.query:

var id = req.query.id; // $_GET["id"]

否则,在NodeJS中,您可以访问req.url和内置的url模块来url.parse它:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

表达特定的简单获取方法

查询字符串(在?之后),例如https://...?user=abc&id=123var express=要求('express');var app=express();app.get('/',函数(req,res){res.send('id:'+req.query.id);});app.listen(3000);查询参数,如https://.../get/users/:idvar express=要求('express');var app=express();app.get('/get/users/:id',函数(req,res){res.send('id:'+req.params.id);});app.listen(3000);

可以使用url.parse使用url模块收集参数

var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;

在expressjs中,

var id = req.query.id;

Eg:

var express = require('express');
var app = express();

app.get('/login', function (req, res, next) {
    console.log(req.query);
    console.log(req.query.id); //Give parameter id
});

我使用的是MEANJS 0.6.0express@4.16,很好

客户:

控制器:

var input = { keyword: vm.keyword };
ProductAPi.getOrder(input)

服务:

this.getOrder = function (input) {return $http.get('/api/order', { params: input });};

服务器

路线

app.route('/api/order').get(products.order);

控制器

exports.order = function (req, res) {
  var keyword = req.query.keyword
  ...