以前在使用java Servlet的时候会经常使用HttpServletRequest对象的getParamter()方法获取HTTP请求的参数,在Node中,不是使用这种方法获取的。
下面我们使用一个例子:
假设HTTP请求有2个参数,分别为username和password
我们在html文件中使用form表单提交到Node中
创建一个js文件,index.js
编写如下代码
var http = require('http'); //引入http模块
var qs = require('querystring'); //引入querystring模块
建立服务器并监听3000端口
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'});
res.end('hello world');
console.log(qs.parse(body).username); //使用qs解析请求体
console.log(qs.parse(body).password);
})
}
}).listen(3000);
编写index.html
<form method="post" action="http://localhost:3000/">
<input name="username" type="text">
<br>
<input name="password" type="text">
<input type="submit" value="Submit">
</form>
运行该程序:
点击submit之后查看控制台
这样,我们就把HTTP POST请求的参数给读取出来啦~