我们可以在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) => { ......

其他回答

这里有很多关于使用request.query访问查询的答案,但是没有人提到它的类型怪癖。查询字符串类型可以是字符串或数组,此类型由用户控制。

例如,使用以下代码:

const express = require("express");
const app = express();

app.get("/", function (req, res) {
  res.send(`Your name is ${(req.query.name || "").length} characters long`);
});

app.listen(3000);

请求/?name=bob将返回您的姓名长3个字符,但请求/?name=bob&name=jane将返回您的名字有2个字符长,因为参数现在是一个数组['bob','jane']。

Express提供了两个查询解析器:简单的和扩展的,它们都将为您提供字符串或数组。我个人认为,应该重写解析器,使其具有一致的类型:所有数组或所有字符串,而不是检查方法的可能副作用或验证类型。

const express = require("express");
const app = express();

const querystring = require("querystring");

// if asArray=false only the first item with the same name will be returned
// if asArray=true all items will be returned as an array (even if they are a single item)
const asArray = false;
app.set("query parser", (qs) => {
  const parsed = querystring.parse(qs);
  return Object.entries(parsed).reduce((previous, [key, value]) => {
    const isArray = Array.isArray(value);
    if (!asArray && isArray) {
      value = value[0];
    } else if (asArray && !isArray) {
      value = [value];
    }

    previous[key] = value;
    return previous;
  }, {});
});

app.get("/", function (req, res) {
  res.send(`Your name is ${(req.query.name || "").length} characters long`);
});

app.listen(3000);

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中,使用req.query。

req.params只获取路由参数,而不获取查询字符串参数。参见快车或帆船文档:

(req.params)检查路由参数,例如:/user/:id(req.query)检查查询字符串参数,例如:?id=12检查URL编码的主体参数(req.body),ex:id=12要使用url编码的请求体,req.body应该是一个对象。这可以通过使用_express.bodyParser中间件来完成。

也就是说,大多数时候,无论参数的来源如何,您都希望获得参数的值。在这种情况下,请使用req.param('fo')。注意,从Express 4开始,这已经被弃用:http://expressjs.com/en/4x/api.html#req.param

无论变量是在路由参数、查询字符串还是编码的请求体中,都将返回该参数的值。

附带说明-如果您的目标是获得所有三种类型的请求参数的交集(类似于PHP的$_request),您只需要将这些参数合并在一起——下面是我在Sails中如何设置的。请记住,path/route-parameters对象(req.params)具有数组财产,因此顺序很重要(尽管在Express4中可能会更改)

表达特定的简单获取方法

查询字符串(在?之后),例如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);

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

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