本篇,我们介绍下http 中req 、res对象,以及如何获取http post参数。
http中req和res分别代表http的请求和响应对象,req对象可以获取请求参数 ,请求头,请求ip,请求referer等。
res对象可以设置http响应头,响应状态码 等。
06_http_req_res.js
//06_http_req_res.js //介绍 http请求中 req、res对象。 req代表请求,res代表响应 //req 请求方式, 请求头 ,请求ip 、请求referer等 // res 写入返回http响应头 var http=require('http'); var server =http.createServer(function (req,res) { // console.log(req); // console.log(res); var reqUrl = req.url; if(reqUrl=='/favicon.ico'){//忽略 ico小图标 return ; } console.log(req.method);//req 请求方式 如GET、 POST 等 console.log(req.headers);//req 请求头 //res 写入返回http响应头 res.writeHead(200,{'content-type':'text/html;charset=utf-8'}); res.end('你好 nodejs'); }); server.listen(3000); console.log('nodejs server run at 3000');
POST 请求的内容全部的都在请求体中,http.ServerRequest 并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所以 node.js 默认是不会解析请求体的,当你需要的时候,需要手动来做。
07_http_post.js
//07_http_post.js //介绍 如何获取post 请求参数 var http=require('http'); var querystring= require('querystring');// var html ="<html><body><form action='/' method='post'> " + "用户名<input type='text' name='username'/> <br/>"+ "密码<input type='password' name='password'/> <br/>"+ "<input type='submit' value='登录'/> <br/>"+ "</form> </body></html>"; var server=http.createServer(function (req,res) { res.writeHead(200,{'content-type':'text/html;charset=utf-8'}); var method=req.method; if(method=='GET'){ res.end(html); return ; } //否则为post 接收表单数据 var postBody = ""; req.on('data', function (chunk) { postBody += chunk; }); req.on('end', function () { // 解析post参数 打印 postBody = querystring.parse(postBody); console.log("username: "+postBody.username); console.log("password: "+postBody.password); res.end("ok"); }); }); server.listen(3000);
上一篇:nodejs之http介绍
下一篇:nodejs之util工具使用
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1