博客详情

nodejs之req、res对象,获取post参数 (原创)

作者: 朝如青丝暮成雪
发布时间:2018-02-23 07:12:43  文章分类:nodejs   阅读(3021)  评论(0)

本篇,我们介绍下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
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号