解析节点.js中的查询字符串
Parsing Query String in 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'
}
但是我不明白如何使用它。谁能解释一下?
您可以在请求回调中使用 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。
还有 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');
从 Node.js 11 开始,遗留 URL API 的 url.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!
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
返回
{ name: 'ryan' }
参考: https://nodejs.org/api/url.html#url_urlobject_query
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"}
另一种无需任何模块即可获取查询参数的方法:
// ...
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.url 和 URLSearchParams 了解详细信息。
- 如何有效地将游戏数据存储在URL查询字符串中
- 从查询字符串参数推断出正确的数据类型
- AngularJS:获取链接中没有哈希的查询字符串值
- AngularJS,如何更改查询字符串
- 如何将activeadmin查询字符串传递给batch_action
- 如何从查询字符串中的输入字段发回文本
- Django在使用AJAX时没有接收到新的查询字符串
- 使用查询字符串方法清除浏览器缓存
- 用于刷新的Javascript更改查询字符串
- 我想将查询字符串变量添加到JSON名称/值对中
- 将查询字符串值从页面传递 asp.net 到 iframe
- jqueryajax生成查询字符串,如果未定义则不通过
- 如何将查询字符串传递到HTML框架
- AngularJs将查询字符串发布到c#控制器
- Jquery - 从查询字符串中获取“#”值之后,而不是在“?”符号值之后获取
- 在 JavaScript 中将查询字符串传递给 Web 服务 (ASP.NET)
- 在查询字符串中查找 where 子句
- POST encodeURI查询字符串内部服务器错误 500
- JavaScript:从具有使用 # 符号的路由的 URL 获取查询字符串
- 更改链接 URL 中的路径名,同时保持查询字符串不变