获取POST请求的参数

本文介绍了如何使用Node.js创建服务器接收并解析HTML表单通过POST提交的数据。通过示例展示了当用户在表单中输入信息并提交后,服务器如何利用querystring模块解析请求体中的数据,并返回相应内容。示例中包括GET请求用于展示表单,POST请求用于接收和处理表单数据。
摘要由CSDN通过智能技术生成

案例一

  • 将html文件中的form表单数据提交到Node中
    index.html 文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单</title>
</head>
<body>
    <form method="post" action="http://localhost:3000/">
        <input name="username" type="text" placeholder="请输入用户名">
        <br>
        <input name="password" type="text" placeholder="请输入密码">
        <input type="submit" value="Submit" >
    </form>
</body>
</html>
  • 建立服务器并监听3000端口
var http = require('http');         //引入http模块
var url = require('url')
var qs = require('querystring');   //引入querystring模块

var server = http.createServer(function (req, res) {
    if (req.url == '/' && req.method == 'POST') {
        var body = '';
        req.on('data', function (chunk) {
            body += chunk;   //读取请求体
        })

        req.on('end', function () {
            console.log(body); // 打印请求体
            res.writeHead(200, {'Content-Type' : 'text/html'}); // 响应报文
            ;
            console.log(qs.parse(body).username);   //使用qs解析请求体
            console.log(qs.parse(body).password);
            res.end('<h1>hello world!</h1>')
        })
    }
}).listen(3000,() => {
    console.log('heihei...')
});
  • 打开html页面,在表单中输入对应的内容,点击Submit:
    在这里插入图片描述
  • 可以在控制台看到如下内容:
heihei...
username=zhangbing&password=123456
zhangbing
123456

其中的 username=zhangbing&password=123456 为请求体
使用querystring中的parse()方法可以解析请求体为:
zhangbing
123456
分别为表单提交的信息

案例2

const http = require('http')
const url = require('url')
const querystring = require('querystring')

const server = http.createServer()

server.on('request',(req,res) => {
    const { pathname, query } = url.parse(req.url, true)
    const method = req.method
    if ( method == 'GET') {
        if ( pathname == '/add') {
            let add = `
                <!DOCTYPE html>
                <html lang="en">
                <head>
	            <meta charset="UTF-8">
	            <title>用户列表</title>
	            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
                </head>
                <body>
	                <div class="container">
		                <h3>添加用户</h3>
		                <form method="post" action="http://localhost:3000/post">
		                    <div class="form-group">
		                        <label>用户名</label>
		                        <input name="name" type="text" class="form-control" placeholder="请填写用户名">
		                    </div>
		                    <div class="form-group">
		                        <label>密码</label>
		                        <input name="password" type="password" class="form-control" placeholder="请输入密码">
		                    </div>
		                    <div class="form-group">
		                        <label>年龄</label>
		                        <input name="age" type="text" class="form-control" placeholder="请填写邮箱">
		                    </div>
		                    <div class="form-group">
		                         <label>邮箱</label>
		                        <input name="email" type="email" class="form-control" placeholder="请填写邮箱">
		                    </div>
		 
		                    <button type="submit" class="btn btn-primary">添加用户</button>
		                </form>
	                </div>
                </body>
            </html>
            `;
            res.end(add)
        }

    } else if ( method == 'POST') {
        if ( pathname == '/post') {
            let formData = ''
            req.on('data', param => {
                formData += param;
            })
            // post 参数接受完毕
            req.on('end', async () => {
                // console.log(formData) // name=123&password=123456&age=20&email=123%40123.com&hobbies=%E8%B6%B3%E7%90%83&hobbies=%E7%AF%AE%E7%90%83
                console.log(querystring.parse(formData)) 
                // [Object: null prototype] {
                //     name: '张兵',
                //     password: '123321',
                //     age: '22',
                //     email: '123@123.com'
                //   }
                res.writeHead(200, {'Conten-Type':'text/html'})                                                // }
                res.end('<h1>hello nodejs</h1>')
            })
        }
    }
})

server.listen(3000,() => {
    console.log('running...')
})

  • 在浏览器地址栏输入:
	http://localhost:3000/add
  • 显示的表单页面如下图所示:
    在这里插入图片描述
  • 输入信息,并点击提交按钮:
    在这里插入图片描述
  • 浏览器响应如下图所示的页面
    在这里插入图片描述
  • 在命令行的控制台打印如下的内容:
[Object: null prototype] {
  name: '张兵',
  password: '123456',
  age: '20',
  email: '123@123.com'
}

总结

可见,借助 querystring.parse()方法确实可以得到表单post参数

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值