node.js 接收post请求
node.js 接收post请求
使用data和end事件来获取post数据,
相关阅读: 与
代码如下:
[javascript]
- var http = require('http');
- var server = http.createServer();
- var querystring = require('querystring');
- var firstPage = function(res){
- res.writeHead(200, {'Content-Type': 'text/html'});
- var html = '<html><body>'+
- '<form action="/login" method="post">'+
- 'name:<input type="text" name="name"> </br>'+
- 'password:<input type="password" name="pwd"></br>'+
- '<input type="submit" value="login">'+
- '</form>'+
- '</body></html>';
- res.end(html);
- }
- var login = function(req, res) {
- var info ='';
- req.addListener('data', function(chunk){
- info += chunk;
- })
- .addListener('end', function(){
- info = querystring.parse(info);
- if(info.name == 'a' && info.pwd =='1'){
- res.end('login success ' + info.name);
- }else{
- res.end('login failed ' + info.name);
- }
- })
- }
- var requestFunction = function (req, res){
- if(req.url == '/'){
- return firstPage(res);
- }
- if(req.url == '/login'){
- if (req.method != 'POST'){
- return;
- }
- return login(req, res)
- }
- }
- server.on('request',requestFunction);
- server.listen(1337, "127.0.0.1");
- console.log('Server running at http://127.0.0.1:1337/');
以上代码实现了一个登录验证用户,将以上代码保存到 example4.js
cmd键入 node example4.js
浏览器地址栏键入 http://127.0.0.1:1337/
如果输入name:a password:1 点击login
如果输入name:a password:2 点击login
该例子 from使用的是默认的application/x-www-form-urlencoded.
评论暂时关闭