在node.js中解析查询字符串

101
在这个“Hello World”示例中:
// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

我怎样从查询字符串中获取参数?

http://127.0.0.1:8000/status?name=ryan

在文档中,他们提到:

node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: { name: 'ryan' }
, pathname: '/status'
}

但是我不明白如何使用它。有人可以解释一下吗?

6个回答

148

在请求回调函数中,您可以使用URL模块parse方法。

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

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

建议您阅读HTTP模块文档,了解在createServer回调中得到的内容。您还应该查看像http://howtonode.org/这样的网站,并尝试使用Express框架来更快地开始使用Node。


谢谢,我测试了,它工作了。感谢提供链接。看来我需要学习更多 :D - L N
这个链接帮助我意识到请求对象是IncomingMessage的一个实例,并且http.IncomingMessage 有一个属性url - Treefish Zhang
在Node.js中,是否有一种方法可以从IncomingMessage对象获取URL参数而不是查询参数? - sumit_suthar

34

还有QueryString模块parse()方法:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

22

从Node.js 11开始,url.parse和其他遗留URL API的方法被废弃(起初只在文档中),使用标准化WHATWG URL API代替。新的API不提供将查询字符串解析为对象的选项。可以使用querystring.parse 方法来实现:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

如果您运行上面的脚本,您可以像这样测试服务器响应,例如:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

9

7

node -v v9.10.1

如果您尝试直接将查询对象打印到控制台,您会收到错误消息:TypeError: Cannot convert object to primitive value

因此,我建议您使用JSON.stringify

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

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

因此,执行curl http://localhost:3000/foo\?fizz\=buzz将返回收到请求:/foo + 方法:GET + 查询:{"fizz":"buzz"}


1
这应该移至顶部。截止于2018年底,此答案恰好解决了 OP 的问题。 - SeaWarrior404

1

另一种获取查询参数的方法是不需要 require 任何模块:

// ...
var server = http.createServer(function (request, response) {

  const requestUrl = new URL(request.url, `http://${request.headers.host}`);
  // Note that searcParams is not a simple JS object.
  // So to get parameter value by its name one should use access methods:
  const nameValue = requestUrl.searchParams.get('name');

  response.writeHead(200, {"Content-Type": "text/plain"});    
  response.end("Hello World\n");
});
// ...

详细信息请参见http.IncomingMessage.urlURLSearchParams


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接