javascriptの後にいくつかのnodejを学び始めて、いくつかの単純なサーバーを作成しています。js/nodejs request.on()とquerystring.parse()を使用したPOSTメソッドの基本的な初心者サーバー
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(「データ」)はnodejsは、データのチャンクを受信するイベントのリスナーを設定する必要があります読みました。この部分上の例でそう:
request.on('data', function (data) {
body += data;
if (body.length > 1e6) {
response.writeHead(413, {'Content-Type':'text/plain'}).end();
request.connection.destroy();
}
それは、再び最初のパラメータ「データ」を取るコールバック関数として二番目のパラメータを取っています。これは私が混乱しているものです。ここで2番目のパラメータで何をしようとしていますか?
2)request.on( '終了')とquerystring.parse()Iは、データのアップロードが完了したことrequest.on( '末端')信号のリスナーを設定nodejs有すること読み取る
ので、以下のコード:request.onインサイド
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);
}
(「終了」)我々はPOSTandと呼ばれる新しい変数がbody
が結合されたすべてのデータの以前の変数であることをquerystring.parse(body)
に等しく、それを設定してください。このquerystring.parse(body)
からどうやって.firstname
(POST.firstname
)を適用し、そのコンポーネントにアクセスしますか?
ありがとうございます。
まだこれらの回答は誰も知りません。 – darkphoton