表单提交后数据无法被nodejs获取?

const fs = require('fs');

const qs = require('querystring');

require('http').createServer(function (req,res) {

    if (req.url === '/'){

        res.writeHead(200,{'content-type':'text/html'});

        res.end(['<form method="post" action="/url">',

            '<input type="text" name="name">',

            '<input type="submit">',

            '<button>Submit</button>',   //

            '</form>'].join(''))

    }

    else if ('/url' === req.url && req.method==='POST') {

        res.writeHead(200,{'content-type':'text/plain'});

        var body = '';

        req.on('data',function (chunk) {

            body += chunk;

        });

        console.log(body)  //无输出

        res.end('hello world' +qs.parse(body).name +'  end')//输出undefined 

    }



}).listen(3000);

为什么在表单中输入数据后提交 无法被node获得,body变量无内容??


胡子哥哥
浏览 851回答 2
2回答

jeck猫

只有req可读流处理完之后才能响应,此时会触发end事件,所以else if逻辑不对,修改后的如下。&nbsp;else if ('/url' === req.url && req.method==='POST') {&nbsp; &nbsp; &nbsp; &nbsp; res.writeHead(200,{'content-type':'text/plain'});&nbsp; &nbsp; &nbsp; &nbsp; var body = '';&nbsp; &nbsp; &nbsp; &nbsp; req.on('data',function (chunk) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body += chunk;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; req.on('end',function(){&nbsp; &nbsp; &nbsp; &nbsp; res.end('hello world' +qs.parse(body).name +'&nbsp; end')&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }

皈依舞

你log输出的时机不对&nbsp; &nbsp; &nbsp; &nbsp; req.on('data',function (chunk) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body += chunk;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(body);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript