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

NodeJS get posted data - No framework

假设我想在 /completed 情况下将发布的数据放入变量中。 我该怎么办? 我能够将数据检索到 request.on("data" ...) 但是如果我将 data 登录到我的 /completed 案例中,data 是空的。

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

您可以:

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 非常有用,我喜欢用它来避免这些代码处理。