一尘不染

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

node.js

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

但是我不知道如何使用它。有人可以解释吗?


阅读 263

收藏
2020-07-07

共1个答案

一尘不染

您可以使用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。

2020-07-07