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

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


当前回答

如果您需要向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;

2014年5月4日更新

此处保留旧答案:https://gist.github.com/stefek99/b10ed037d2a4a323d638


1) 安装express:npm安装express

应用程序.js

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

app.get('/endpoint', function(request, response) {
    var id = request.query.id;
    response.end("I have received the ID: " + id);
});

app.listen(3000);
console.log("node express app started at http://localhost:3000");

2) 运行app:node app.js

3) 在浏览器中访问:http://localhost:3000/endpoint?id=something

我收到了ID:某物


(自从我的回答以来,很多事情都发生了变化,我相信这是值得的,让事情保持最新)

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

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

//etc. example.com/user/000000?sex=female

app.get('/user/:id', function(req, res) {

  const query = req.query;// query = {sex:"female"}

  const params = req.params; //params = {id:"000000"}

})

你应该可以这样做:

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

http.createServer(function(req,res){
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query); //{Object}

    res.end("End")
})