Node.js学习笔记:表单提交

get提交

因为get提交过来的表单都是直接显示在url地址中的,所以直接解析req.url传过来的url就可以直接得到数据,如下所示:

const http = require("http");
const url = require("url");
let server = http
    .createServer((req, res) => {
        let myUrl = url.parse(req.url, true);
        let obj = myUrl.query;
        res.end("Hello World");
    })
    .listen(80, "127.0.0.1");

post提交

post提交的数据不会直接显示在url中,而且node.js为了保证速度,提交数据的时候是分段提交,就需要用req.on()方法进行监听,最后得到的dataObj就是提交过来的表单数据。

const http = require("http");
const querystring = require("querystring");
let server = http
    .createServer((req, res) => {
        if (req.url === "/postmsg" && req.method.toLowerCase() === "post") {
            let allData = "";
            req.on("data", buf => {
                allData += buf;
            });
            req.once("end", () => {
                let dataObj = querystring.parse(allData);
                console.log(dataObj);
            });
        }
        res.end("Hello World");
    })
    .listen(80, "127.0.0.1");

提交的文件处理

formidable框架

如果表单中包含图片或者其他类型的文件,就需要接收文件。直接引入一个formidable框架。

const formidable = require("formidable"),
    http = require("http"),
    util = require("util"),
    fs = require("fs");
let server = http
    .createServer((req, res) => {
        if (req.url === "/postmsg" && req.method.toLowerCase() === "post") {
            let form = new formidable.IncomingForm();
            form.uploadDir = "./uploads";
            form.parse(req, (err, fields, files) => {
                //直接改成照片的名字
                let oldName = __dirname + "/" + files.photo.path;
                let newName = __dirname + "/uploads/" + files.photo.name;
                fs.rename(oldName, newName, err => {
                    if (!err) {
                        res.writeHead(200, {
                            "content-type": "text/plain;charset=utf-8"
                        });
                        res.write("received upload:\n\n");
                        res.end(util.inspect({ fields: fields, files: files }));
                    } else {
                        throw err;
                    }
                });
            });
        }
    })
    .listen(80, "127.0.0.1");

生成独一无二的时间戳

uuidvl

你可能感兴趣的:(Node.js学习笔记:表单提交)