繁体   English   中英

使用 request.on() 和 querystring.parse() POST 方法的 js/nodejs 基本初学者服务器

[英]js/ nodejs basic beginner server for POST method using request.on() and querystring.parse()

在 javascript 之后,我开始在我的 web 类中学习一些 nodejs 来制作一些简单的服务器,下面是这个例子:

var http = require('http');
var url = require('url');
var querystring = require('querystring');


function onRequest(request, response) {

    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;  // data sent via http protocol will always be sent as a string and can be concatenated
            // if body > 1e6 === 1* Math.pow(10,6) ~~~ 1MB
            // flood attack or faulty client
            // (code 413: request entity too large), kill request
            if (body.length > 1e6) {
                response.writeHead(413, {'Content-Type':'text/plain'}).end();
                request.connection.destroy();
            }
        });            // end of data communication: body will contain all the parameters of the query 

        request.on('end',function(){
            var POST = querystring.parse(body);
            // now to get the different parameters use // POST.<field name>  e.g. POST.user
            response.end('Hello, ' + POST.firstname + ' ' + POST.lastname);

        });
    }


}

var server = http.createServer(onRequest);

server.listen(3000);

到目前为止,我已经理解了,但是在查找和理解此代码的 request.on() 和 querystring.parse() 部分时遇到了麻烦。 我将在我混淆的确切部分下方突出显示它们以更清晰。

1) request.on()

所以我读过 request.on('data') 会让 nodejs 为接收数据块的事件设置一个监听器。 所以用上面这部分的例子:

request.on('data', function (data) {
                body += data;  
                if (body.length > 1e6) {
                    response.writeHead(413, {'Content-Type':'text/plain'}).end();
                    request.connection.destroy();
                }

它采用第二个参数作为回调函数,再次采用第一个参数“数据”。 这就是我所困惑的,它在这里试图用第二个参数做什么?

2) request.on('end') 和 querystring.parse()

我读到 request.on('end') 将让 nodejs 为数据上传完成的信号设置一个监听器,所以下面的代码:

request.on('end',function(){
                var POST = querystring.parse(body);
                // now to get the different parameters use // POST.<field name>  e.g. POST.user
                response.end('Hello, ' + POST.firstname + ' ' + POST.lastname);

            }

在 request.on('end') 中,我们创建了一个名为 POST 的新变量并将其设置为等于querystring.parse(body)其中body是所有数据组合的前一个变量。 它如何从这个querystring.parse(body)并在其上应用.firstname ( POST.firstname ) 并访问它的那个组件?

提前致谢。

对于你的第一个问题:

它采用第二个参数作为回调函数,再次采用第一个参数“数据”。 这就是我所困惑的,它在这里试图用第二个参数做什么?

因此,您在这里所做的是定义每次request触发data事件时调用的侦听器函数。 您可以通过以下方式更清楚地看到它:

request.on('data', onChunkReceived)

function onChunkReceived (data) {
  body += data

  if body > 1e6 === 1* Math.pow(10,6) ~~~ 1MB
    if (body.length > 1e6) {
      response.writeHead(413, {'Content-Type':'text/plain'}).end();
      request.connection.destroy();
    }
}

你正在做的是定义一个函数,它接受一个data参数; 不要因为事件名称和选择的参数名称相同而过于纠结; 没有理由您不能随意命名它:

request.on('data', onChunkReceived)

function onChunkReceived (chunk) {
  body += chunk

  if body > 1e6 === 1* Math.pow(10,6) ~~~ 1MB
    if (body.length > 1e6) {
      response.writeHead(413, {'Content-Type':'text/plain'}).end();
      request.connection.destroy();
    }
}

...会以完全相同的方式行事。 再说一遍: data是事件的名称,您正在定义一个函数,该函数在服务器接收数据时接收每个数据块; 在上面的示例中,该函数只是内嵌的匿名函数,因为我已经重新格式化了上面的代码片段,它是一个单独的命名函数。

现在回答你的第二个问题:

在 request.on('end') 中,我们创建了一个名为 POST 的新变量并将其设置为等于 querystring.parse(body) ,其中 body 是所有数据组合的前一个变量。 它如何从这个 querystring.parse(body) 开始并在其上应用 .firstname (POST.firstname) 并访问它的那个组件?

querystring.parse方法采用特定格式的字符串,并将其解析为 Javascript 对象。 查询字符串上Node.js 文档比我在这里解释的要好得多。 因此,我只能假设您正在使用的示例期望正文采用特定格式,即形式编码意味着它采用以下格式:

firstname=Dan&lastname=Takahashi

当您对该字符串调用querystring.parse时,您将返回一个如下所示的对象:

POST = {
  "firstname": "Dan",
  "lastname": "Takahashi"
}

然后你可以像上面所说的那样寻址: POST.firstname将是“Dan”和POST.lastname将是“Takahashi”。

问题 1 和问题 2 处理 http 请求数据流,并允许您注入代码以执行自定义活动,例如将流保存到缓冲区/var 以备后用。

如果你想查询 POST 参数,你可以简单地使用 bodyparser 节点模块https://github.com/expressjs/body-parser

使用对象点符号查询参数。 例如 req.body.form_field_name

body-parser 是一个很好的模块,用于快速访问在 POST/PUT 方法中传递的数据。

Express 会隐藏原始正文数据,您需要使用类似于 body-parser 的模块来获取访问权限。 请注意,这是正文内容的只读副本。

干杯。

PS 如果 body-parser 不能满足您的迫切需求,请查看

  1. github.com/stream-utils/raw-body
  2. github.com/moscartong/express-rawbody

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM