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


86

在此“ 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'
}

但是我不知道如何使用它。谁能解释?

Answers:


136

您可以使用parse从方法URL模块在请求回调。

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
LN

这个链接可以帮助我实现这一点[t]he request object is an instance of IncomingMessage,并且http.IncomingMessage 具有属性 url
树鱼张

有什么方法可以从node.js中的IncomingMessage对象获取URL参数而不是查询参数
sumit_suthar

30

还有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');


6

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会回来Request received on: /foo + method: GET + query: {"fizz":"buzz"}


1
这应该移到顶部。截至2018年底,此答案完全解决了OP的问题
SeaWarrior404 '18

4

从Node.js 11开始,不赞成使用Legacy URL APIurl.parse和其他方法(首先仅在文档中使用),而采用了标准化的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!
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.