使用request.on()进行GET请求

时间:2018-07-09 23:19:36

标签: javascript node.js

在处理GET请求时,我应该使用request.on()吗?

例如,在我的main.js中,

var http = require('http');
var dispatcher = require('./public/javascript/dispatcher.js');
var serverPort = 8124;
http.createServer(function (request, response) {
  dispatcher.deal(request, response);
}).listen(serverPort);

dispatcher.js中,我有

module.exports = {

    deal: function(request, response) {
        if(request.method === "GET") {  // WITHIN THIS BLOCK
            var get = require('./get.js');
            // Pass data to the appropriate function
            get.do(request, response);
        } else if(request.method === "POST") { 
            var qs = require('querystring');
            var requestBody = '';

            request.on('data', function(data) {
                requestBody += data;
            });

            request.on('end', function() {
                var formData = qs.parse(requestBody);
                var post = require('./post.js');

                // Pass data to the appropriate function
                post.doing(request, response, formData);
            });
        }
    } // End deal
} // End exports

因此,为了扩展我最初的问题和发布的代码,该程序可以在没有request.on()的情况下正常运行。我的猜测是,由于没有数据可以等待GET请求,因此不需要require.on('end', ...)。欢迎任何澄清,建议或建议!

0 个答案:

没有答案