Node.js-在简单的FormData Ajax帖子上两次调用request.onend

时间:2019-04-16 19:11:22

标签: node.js ajax form-data

我一直在尝试将简单的ajax formdata发布到nodejs服务器...

const http = require('http');

const { parse } = require('querystring');

let
count = 1,
log = function ( body ) {

    let bd = parse(body);
    console.log(Date.now());
    console.log(++count);
    console.log(bd);

};

http.createServer((req, res) => {

    if (req.method === 'POST') {

     let body = '';

        req.on('data', chunk => {

            body += chunk.toString();

        });

        req.on('end', () => {

            log(body);
            res.end("Ok");

        });

    } else {

        res.end(`

            <!doctype html>

            <html>

            <body>

                <form action="/" method="post" onsubmit="return go(this);">

                    <input type="text" name="f01" /><br />
                    <input type="text" name="f02" /><br />
                    <input type="text" name="f03" /><br />
                    <button>Send</button>

                </form>
                <script>

                function go(f) {

                 let
                 request = new XMLHttpRequest(),
                 formData = new FormData(f);

                 request.onload = function ( ret ) {

                  alert(ret.target.responseText);

                 }

                 request.open('POST', f.action);
                 request.send(formData);

                }

               </script>

            </body>

            </html>

        `);

    }

}).listen(3000);

问题是,似乎req.on('end')总是被调用两次。

我的日志功能第一次向(我)输出诸如:

[对象:空原型] {   '----------------------------- 7e31ba3a10238 \ r \ nContent-Disposition:表单数据;名称':    '“ f01” \ r \ n \ r \ na \ r \ n ----------------------------- 7e31ba3a10238 \ r \ n内容-处置:形式数据; name =“ f02” \ r \ n \ r \ nb \ r \ n ----------------------------- 7e31ba3a10238 \ r \ nContent-Disposition:表单数据; name =“ f03” \ r \ n \ r \ nc \ r \ n ----------------------------- 7e31ba3a10238-\ r \ n'}

第二次还可以:

[对象:空原型] {f01:“ a”,f02:“ b”,f03:“ c”}

我在做什么错了?

0 个答案:

没有答案