parsingnode.js中的查询string

在这个“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/"); 

我怎样才能从查询string中获取参数?

 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' } 

但我不明白如何使用它。 谁能解释一下?

提前致谢

您可以使用请求callback中的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); 

我build议你阅读HTTP模块文档,以了解你在createServercallback中得到什么。 你也应该看看像http://howtonode.org/这样的站点,并且检查Express框架以更快地开始使用Node。;

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