美文网首页
六、post请求

六、post请求

作者: 向上而活 | 来源:发表于2019-08-22 23:09 被阅读0次

POST请求
相比较GET请求,POST请求比较复杂。因为 Node.js认为,使用POST请求时,数据量会比较多。为了追求极致的效率,它将数据拆分成为了众多小的数据块( chunk),然后通过特定的事件,将这些小数据块有序传递给回调函数。

var postdata="";
reg. addlistener("data",function(chunk){
postdata +=chunk;
})
reg. addlistener("end", function(){
console. log(postdata);
var param=querystring.parse(postdata);
res. writehead(200, {"content-type": "text/html; charset=utf-8"})
res.end(param.name) ;
})
var alldata="";
//下面是post请求接收的一个公式
//node为了追求极致,它是一个小段一个小段接收的。
//接受了ー小段,可能就给别人去服务了。防止一个过大的表单阻塞了整个进程
req.addlistener("data", function(chunk){
alldata+=chunk;
})
//全部传输完毕
req. addlistener("end", function(){
console. log(alldata.tostring();
res.end("succ");
})

原生写POST处理,比较复杂,要写两个监听。文件上传业务比较难写。所以,用第三方模块:formidable 。

只要涉及文件上传,那么form标签要加一个属性:

<form action=p: /127.0.0.1/dopost"method=post "enctype"multipar/form-data">.

POST请求提交表单数据与上传图片
HTML 部分

<body>
        <form action="http://127.0.0.1/dopost" method="post" enctype="multipart/form-data">
            <!-- 只要涉及文件上传 form标签要加 enctype="multipart/form-data"-->
            <p>
                姓名:<input type="text" name="name">
            </p>
            <p>
                性别:<input type="radio" name="sex" value="男">男
                <input type="radio" name="sex" value="女">女
            </p>
            <p>爱好:
                <input type="checkbox" name="hb" value="睡觉"> 睡觉
                <input type="checkbox" name="hb" value="游戏"> 游戏
                <input type="checkbox" name="hb" value="旅游"> 旅游
            </p>
            <p>
                <input type="file" name="img">上传图片
            </p>
            <p>
                <input type="submit">
            </p>
        </form>
    </body>

JS部分(不包含接收图片的逻辑)

var http = require("http");
var querystring = require("querystring");

//创建服务器
var server = http.createServer(function(req, res) {
    //如果访问地址是/dopost 并且请求类型是这个POST
    if (req.url == "/dopost" && req.method == "POST") {
 //注意:'/dopost' 前面带 / ,  'POST'是大写
        //拼接请求到的数据
        var alldata = "";
        //下面是post请求接收的一个公式
        //node为了追求极致,它是一个小段一个小段接收的。
        //接收了一个小段,可能就给别人去服务了。防止一个过大的表单阻塞I/O
        req.addListener("data", function(chunk) {
            alldata += chunk;
            //console.log(chunk);
        })
        //数据接收完成
        req.addListener("end", function(chunk) {
            var datastring = alldata.toString();
            //console.log(datastring);
            res.end("succ")
            //将datastring转成一个对象
            var dataobj = querystring.parse(datastring);
            // console.log(dataobj)
            // console.log(dataobj.name)
            // console.log(dataobj.sex)
            // console.log(dataobj.hb)
        })
    } else {
        console.log("有错误");
        // console.log(req.url);
        // console.log(req.method);
    }

})
server.listen(80, "127.0.0.1");

JS部分(包含接收图片的逻辑)

var http = require("http");
var querystring = require("querystring");
var formidable = require('formidable'); //需要安装 npm install formidable@latest
var util = require("util");
var fs = require("fs");
var sd = require("silly-datetime"); //需要安装 npm install silly-datetime@latest
var path = require("path");
//创建服务器
var server = http.createServer(function(req, res) {
    //如果访问地址是/dopost 并且请求类型是这个POST
    if (req.url == "/dopost" && req.method.toLowerCase() == "post") {
        //creates a new incoming form
        var form = new formidable.IncomingForm();
        //设置文件上传存放地址
        form.uploadDir = "./imgs";
        //执行里面的回掉函数的时候,表单已经完全接受完毕
        form.parse(req, function(err, fields, files) {
            //所有文本域、单选框 都在fields存放;
            //所有文件域 都在files
            console.log(fields);
            console.log(files);
            //输出的结果         
            // { name: 'yangyi', sex: '男', hb: '旅游' }
            // { img:
            //    File {
            //      _events: [Object: null prototype] {},
            //      _eventsCount: 0,
            //      _maxListeners: undefined,
            //      size: 19907,
            //      path: 'imgs\\upload_beb355942d36d421df58d0fa0a34d262',
            //      name: 'logo.png',
            //      type: 'image/png',
            //      hash: null,
            //      lastModifiedDate: 2019-08-03T03:54:50.260Z,
            //      _writeStream:
            //       WriteStream {
            //         _writableState: [WritableState],
            //         writable: false,
            //         _events: [Object: null prototype] {},
            //         _eventsCount: 0,
            //         _maxListeners: undefined,
            //         path: 'imgs\\upload_beb355942d36d421df58d0fa0a34d262',
            //         fd: null,
            //         flags: 'w',
            //         mode: 438,
            //         start: undefined,
            //         autoClose: true,
            //         pos: undefined,
            //         bytesWritten: 19907,
            //         closed: false } } }
            // console.log(util.inspect({
            //  fields: fields,
            //  files: files
            // }));
            //时间 使用了第三方模块 silly-datatime
            var ttt = sd.format(new Date(), "YYYYMMDDHHmmss");
            var ran = parseInt(Math.random() * 89999 + 10000);
            var extname = path.extname(files.img.name);
            // console.log('CSyangyi' + ttt + ran + extname);
            // console.log(__dirname);
            //执行给上传的img改名
            var oldpath = __dirname + "/" + files.img.path;
            //新的路由由三个部分组成:时间戳 随机数 拓展名
            var newpath = __dirname + "/imgs/" + ttt + ran + extname;
            //console.log(oldpath, newpath);
            //改名
            fs.rename(oldpath, newpath, function(err) {
                if (err) {
                    throw Error("改名失败");
                }
                res.writeHead(200, {
                    'content-type': 'text/plain'
                });
                res.end('succ');
            });


        });
    } else if (req.url == "/") {
        //呈递form.html页面
        fs.readFile("./form.html", function(err, data) {
            res.writeHead(200, {
                "content-type": 'text/html'
            });
            res.end(data);
        })
    } else {
        res.writeHead(404, {
            'content-type': 'text/html'
        });
        res.end("404");
    }
})
server.listen(80, "127.0.0.1");

相关文章

  • 六、post请求

    POST请求相比较GET请求,POST请求比较复杂。因为 Node.js认为,使用POST请求时,数据量会比较多。...

  • 六:node——post请求

    post请求的数据比get大的多,所以post是分段发送请求的post方式接收数据用 res.on举个栗子: 结果...

  • iOS请求方法和网络安全

    GET和POST请求 GET和POST请求简介 GET请求模拟登陆 POST请求模拟登陆 GET和POST的对比 ...

  • java发送http请求

    restTemplate get请求 post请求 apache.http.client get请求 post请求...

  • gf框架 ghttp使用

    案例中包含以下内容 get请求 get请求携带参数 post请求携带参数 post请求发送xml数据 post请求...

  • iOS请求方法和网络安全

    GET和POST请求GET和POST请求简介GET请求模拟登陆POST请求模拟登陆GET和POST的对比保存用户信...

  • WKWebView发送POST请求

    WKWebView发送POST请求 WKWebView发送POST请求

  • Get和Post的区别

    Get请求和Post请求区别如下: Post请求比Get请求更安全,get请求直接将参数放置在URL中,post请...

  • Python 网络工具包 - requests

    安装与加载 网络请求 - Request GET 请求 POST 请求 - form-data POST 请求 -...

  • curl相关操作

    GET请求 POST请求 POST请求,提交json格式数据 curl 的使用

网友评论

      本文标题:六、post请求

      本文链接:https://www.haomeiwen.com/subject/oodasctx.html