微信登录

Web 服务器开发 - 处理请求 - 解析请求参数

Node.js Web 服务器开发 - 处理请求 - 解析请求参数

在 Node.js 开发 Web 服务器时,处理客户端请求并解析其中的参数是一项非常重要的任务。请求参数通常分为两种类型:查询字符串参数(Query String Parameters)和请求体参数(Request Body Parameters)。下面我们将详细介绍如何在 Node.js 中解析这两种类型的参数。

1. 创建基本的 HTTP 服务器

首先,我们需要创建一个基本的 HTTP 服务器,为后续解析请求参数做准备。以下是一个简单的示例代码:

  1. const http = require('http');
  2. const server = http.createServer((req, res) => {
  3. res.writeHead(200, { 'Content-Type': 'text/plain' });
  4. res.end('Hello, World!\n');
  5. });
  6. const port = 3000;
  7. server.listen(port, () => {
  8. console.log(`Server running at http://localhost:${port}/`);
  9. });

在上述代码中,我们使用 http 模块创建了一个简单的 HTTP 服务器,当有客户端请求时,服务器会返回一个包含 “Hello, World!” 的响应。

2. 解析查询字符串参数

查询字符串参数通常出现在 URL 的问号(?)后面,多个参数之间用与号(&)分隔。例如:http://example.com/api?name=John&age=30

我们可以使用 url 模块来解析查询字符串参数。以下是一个示例代码:

  1. const http = require('http');
  2. const url = require('url');
  3. const server = http.createServer((req, res) => {
  4. const parsedUrl = url.parse(req.url, true);
  5. const queryParams = parsedUrl.query;
  6. res.writeHead(200, { 'Content-Type': 'application/json' });
  7. res.end(JSON.stringify(queryParams));
  8. });
  9. const port = 3000;
  10. server.listen(port, () => {
  11. console.log(`Server running at http://localhost:${port}/`);
  12. });

在上述代码中,我们使用 url.parse(req.url, true) 方法来解析请求的 URL,并将第二个参数设置为 true,表示自动解析查询字符串参数。然后,我们可以通过 parsedUrl.query 获取解析后的查询字符串参数对象。最后,我们将参数对象以 JSON 格式返回给客户端。

3. 解析请求体参数

请求体参数通常出现在 POST、PUT 等请求中,客户端会将数据放在请求体中发送给服务器。解析请求体参数稍微复杂一些,因为请求体数据是分块传输的。

我们可以使用 querystring 模块来解析表单数据(application/x-www-form-urlencoded 格式),使用 JSON.parse 方法来解析 JSON 数据(application/json 格式)。以下是一个示例代码:

  1. const http = require('http');
  2. const querystring = require('querystring');
  3. const server = http.createServer((req, res) => {
  4. if (req.method === 'POST') {
  5. let body = '';
  6. req.on('data', (chunk) => {
  7. body += chunk.toString();
  8. });
  9. req.on('end', () => {
  10. const contentType = req.headers['content-type'];
  11. let params;
  12. if (contentType === 'application/x-www-form-urlencoded') {
  13. params = querystring.parse(body);
  14. } else if (contentType === 'application/json') {
  15. try {
  16. params = JSON.parse(body);
  17. } catch (error) {
  18. res.writeHead(400, { 'Content-Type': 'text/plain' });
  19. res.end('Invalid JSON data');
  20. return;
  21. }
  22. }
  23. res.writeHead(200, { 'Content-Type': 'application/json' });
  24. res.end(JSON.stringify(params));
  25. });
  26. } else {
  27. res.writeHead(405, { 'Content-Type': 'text/plain' });
  28. res.end('Method Not Allowed');
  29. }
  30. });
  31. const port = 3000;
  32. server.listen(port, () => {
  33. console.log(`Server running at http://localhost:${port}/`);
  34. });

在上述代码中,我们首先判断请求方法是否为 POST。如果是 POST 请求,我们通过监听 data 事件来收集请求体数据,监听 end 事件表示数据接收完毕。然后,根据请求头中的 Content-Type 字段来判断数据格式,使用相应的方法进行解析。最后,将解析后的参数对象以 JSON 格式返回给客户端。

总结

参数类型 出现位置 解析方法 示例代码
查询字符串参数 URL 问号后面 url.parse(req.url, true).query const parsedUrl = url.parse(req.url, true); const queryParams = parsedUrl.query;
请求体参数(表单数据) 请求体中,application/x-www-form-urlencoded 格式 querystring.parse(body) const params = querystring.parse(body);
请求体参数(JSON 数据) 请求体中,application/json 格式 JSON.parse(body) const params = JSON.parse(body);

通过以上方法,我们可以在 Node.js 中轻松地解析请求参数,从而更好地处理客户端请求。