微信登录

表单处理 - 接收表单数据 - 处理 HTML 表单提交

表单处理 - 接收表单数据 - 处理 HTML 表单提交

在 Web 开发中,表单是用户与网站进行交互的重要方式之一。用户可以通过表单输入信息,如用户名、密码、留言等,然后将这些信息提交给服务器进行处理。Node.js 作为一个强大的服务器端 JavaScript 运行环境,为我们处理表单提交提供了很好的支持。本文将详细介绍如何使用 Node.js 处理 HTML 表单提交,并给出相应的演示代码。

1. 表单提交的基本原理

当用户在 HTML 表单中输入信息并点击提交按钮时,浏览器会将表单数据打包,并根据表单的 method 属性(GETPOST)将数据发送到表单的 action 属性指定的 URL。服务器接收到这些数据后,需要对其进行解析和处理。

GET 和 POST 请求的区别

请求方法 特点 适用场景
GET 数据会附加在 URL 后面,格式为 ?key1=value1&key2=value2,有长度限制,不安全(数据会暴露在 URL 中) 获取数据,如搜索、分页等
POST 数据会放在请求体中,没有长度限制,相对安全 提交敏感信息,如登录、注册等

2. 使用 Node.js 处理表单提交

2.1 处理 GET 请求的表单提交

以下是一个简单的示例,展示了如何使用 Node.js 处理 GET 请求的表单提交。

  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>GET 表单示例</title>
  8. </head>
  9. <body>
  10. <form action="/submit" method="get">
  11. <label for="name">姓名:</label>
  12. <input type="text" id="name" name="name">
  13. <br>
  14. <label for="age">年龄:</label>
  15. <input type="number" id="age" name="age">
  16. <br>
  17. <input type="submit" value="提交">
  18. </form>
  19. </body>
  20. </html>
  1. // server.js
  2. const http = require('http');
  3. const url = require('url');
  4. const server = http.createServer((req, res) => {
  5. const parsedUrl = url.parse(req.url, true);
  6. if (req.method === 'GET' && parsedUrl.pathname === '/submit') {
  7. const query = parsedUrl.query;
  8. const name = query.name;
  9. const age = query.age;
  10. res.writeHead(200, { 'Content-Type': 'text/plain' });
  11. res.end(`你提交的姓名是:${name},年龄是:${age}`);
  12. } else if (parsedUrl.pathname === '/') {
  13. const fs = require('fs');
  14. fs.readFile('index.html', (err, data) => {
  15. if (err) {
  16. res.writeHead(500, { 'Content-Type': 'text/plain' });
  17. res.end('内部服务器错误');
  18. } else {
  19. res.writeHead(200, { 'Content-Type': 'text/html' });
  20. res.end(data);
  21. }
  22. });
  23. } else {
  24. res.writeHead(404, { 'Content-Type': 'text/plain' });
  25. res.end('未找到该页面');
  26. }
  27. });
  28. const port = 3000;
  29. server.listen(port, () => {
  30. console.log(`服务器运行在 http://localhost:${port}`);
  31. });

代码解释

  • HTML 部分:创建了一个简单的表单,使用 GET 方法将数据提交到 /submit 路径。
  • Node.js 部分
    • 使用 http 模块创建一个服务器。
    • 当接收到 GET 请求且路径为 /submit 时,使用 url.parse 方法解析 URL 中的查询参数,获取用户提交的姓名和年龄,并返回响应。
    • 当路径为根路径 / 时,读取 index.html 文件并返回给客户端。
    • 对于其他路径,返回 404 错误。

2.2 处理 POST 请求的表单提交

处理 POST 请求的表单提交稍微复杂一些,因为数据是放在请求体中的,需要通过监听 dataend 事件来获取完整的请求体数据。

  1. <!-- post_index.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>POST 表单示例</title>
  8. </head>
  9. <body>
  10. <form action="/post_submit" method="post">
  11. <label for="username">用户名:</label>
  12. <input type="text" id="username" name="username">
  13. <br>
  14. <label for="password">密码:</label>
  15. <input type="password" id="password" name="password">
  16. <br>
  17. <input type="submit" value="提交">
  18. </form>
  19. </body>
  20. </html>
  1. // post_server.js
  2. const http = require('http');
  3. const server = http.createServer((req, res) => {
  4. if (req.method === 'POST' && req.url === '/post_submit') {
  5. let body = '';
  6. req.on('data', (chunk) => {
  7. body += chunk.toString();
  8. });
  9. req.on('end', () => {
  10. const formData = new URLSearchParams(body);
  11. const username = formData.get('username');
  12. const password = formData.get('password');
  13. res.writeHead(200, { 'Content-Type': 'text/plain' });
  14. res.end(`你提交的用户名是:${username},密码是:${password}`);
  15. });
  16. } else if (req.url === '/') {
  17. const fs = require('fs');
  18. fs.readFile('post_index.html', (err, data) => {
  19. if (err) {
  20. res.writeHead(500, { 'Content-Type': 'text/plain' });
  21. res.end('内部服务器错误');
  22. } else {
  23. res.writeHead(200, { 'Content-Type': 'text/html' });
  24. res.end(data);
  25. }
  26. });
  27. } else {
  28. res.writeHead(404, { 'Content-Type': 'text/plain' });
  29. res.end('未找到该页面');
  30. }
  31. });
  32. const port = 3001;
  33. server.listen(port, () => {
  34. console.log(`服务器运行在 http://localhost:${port}`);
  35. });

代码解释

  • HTML 部分:创建了一个使用 POST 方法的表单,将数据提交到 /post_submit 路径。
  • Node.js 部分
    • 当接收到 POST 请求且路径为 /post_submit 时,监听 data 事件,将每次接收到的数据块拼接成完整的请求体。
    • 监听 end 事件,当请求体接收完毕后,使用 URLSearchParams 解析请求体数据,获取用户名和密码,并返回响应。
    • 对于根路径 /,读取 post_index.html 文件并返回给客户端。
    • 对于其他路径,返回 404 错误。

3. 总结

通过以上示例,我们了解了如何使用 Node.js 处理 HTML 表单提交。处理 GET 请求相对简单,只需解析 URL 中的查询参数;处理 POST 请求需要监听 dataend 事件来获取完整的请求体数据。在实际开发中,我们可以使用 Express 等框架来更方便地处理表单提交。

希望本文能帮助你更好地理解和掌握 Node.js 处理表单提交的方法。