NodeJS获取发布的数据 - 没有框架

时间:2015-03-24 23:04:32

标签: node.js http-post

假设我希望将数据发布到/completed案例中的变量中。 我该怎么办? 我能够将数据检索到request.on(&#34; data&#34; ...)但如果我将data记录到我的/completed案例中,则data为空。< / p>

var http = require('http');
http.createServer( function(request, response) {
    var data = "";
    if(request.method == 'POST') {
        request.on('data', function(chunk) {
            console.log('Received data:', chunk.toString());
            data += chunk.toString();
        });
        request.on('end', function() {
            console.log('Complete data:', data);
        });
    }
    switch (request.url) {
        case "/":
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write("<a href='/form'>Go to form</a>");
            response.end();
            break;
        case "/form" :
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write("<form method='POST' action='/completed'>");
            response.write("<input type='text' name='data1'/><hr/>");
            response.write("<input type='text' name='data2'/><hr/>");
            response.write("<input type='text' name='data3'/><hr/>");
            response.write("<input type='file' name='data4'/><hr/>");
            response.write("<input type='submit' value='Send'/>");
            response.end("</form>");
            break;
        case "/completed":
            console.log(request);
            response.writeHead(200, {'Content-Type': 'text/html'});

            // var post = ?

            response.end();
            break;
        default:
            response.writeHead(403, {'Content-Type': 'text/html'});
            response.end("Forbidden");
            break;
    }

}).listen(1337);

结果

Received data: data1=dfs&data2=ds&data3=dvbcfgxrtgdw
Complete data: data1=dfs&data2=ds&data3=dvbcfgxrtgdw

1 个答案:

答案 0 :(得分:1)

你可以:

app.use(express.bodyParser());

app.post('/completed', function(request, response){

    console.log(request.body.user.name);
    console.log(request.body.user.email);

});

假设你使用快递。

否则,您必须使用req.on数据和结束事件:

if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
    });
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('post received');
}

您还可以添加:

qs = require('querystring');

var json = qs.parse(body);

util.log("json: " + json);

检索参数。

Express非常有用,我喜欢用它来避免这种代码处理。