在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 表單提交后數(shù)據(jù)無法被nodejs獲取?

表單提交后數(shù)據(jù)無法被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);

為什么在表單中輸入數(shù)據(jù)后提交 無法被node獲得,body變量無內(nèi)容??

回答
編輯回答
短嘆

你log輸出的時機不對

        req.on('data',function (chunk) {
            body += chunk;
            console.log(body); 
        });
        
2017年6月27日 19:43
編輯回答
你好胸

只有req可讀流處理完之后才能響應(yīng),此時會觸發(fā)end事件,所以else if邏輯不對,修改后的如下。

 else if ('/url' === req.url && req.method==='POST') {
        res.writeHead(200,{'content-type':'text/plain'});
        var body = '';
        req.on('data',function (chunk) {
            body += chunk;
        });
        req.on('end',function(){
        res.end('hello world' +qs.parse(body).name +'  end')
        })
        
    }
2018年2月28日 10:41