Node.js missing message data in async request

I am making a simple form in Node.js. Everything else works correctly, but the function that should receive the data after the request will never be called. Here is the relevant code snippet:

if (request.method == 'POST') { var body = ''; console.log(request.body); request.on('data', function (chunk) { console.log("got the post request data"); //nothing logged to console body += chunk; }); request.on('end', onRequestEnd(body, response)); } 

The onRequestEnd function calls, but later my code breaks when there is only an empty string in the parameter body. Is the "data" keyword spelled correctly?

The code has been modified from the answer here: How do you retrieve POST data in Node.js? . If necessary, send more.

+4
source share
2 answers

After many disappointments, I myself solved the problem!

I changed the line:

 request.on('end', onRequestEnd(body, response)); 

in

 request.on('end', function() { onRequestEnd(body, response); }); 

This has something to do with callbacks. I'm not quite sure why this works, and the other is not. Here's how I feel: http://www.masti-xpress.com/images/Story-of-Every-Programmer.jpg

+1
source

I will tell you how I solved the problem with this. I had a different look at this, and I will share it too. I would like to have something similar in my "view".

 app('/urlToView', function(req, response){ request.on('end', function() { var post = **request.data;** //sanitize data resolver.renderTemplateOr404('start.html', post, request, response); }); } 

The request.data strong> icon is what you should notice here. However, I have not yet decided how not to have request.on('end'...) in my view.

The reason why console.log () will be the way you handle the callback from the function in which you are doing all this.

I grabbed the request before it lands in my opinion when I started the server

self.preProcess(self, request, response);

and

 preProcess: function onRequest(app, request, response){ processor.preRequest(request); } 

and finally int preRequest (), I do

 if (request.method === 'POST') { var postdata = ""; request.on('data', function(postdataChunk){ postdata += postdataChunk; }); request.on('end', function(){ _transformRequest(request, _transformPostdata(postdata)); //this is to set the data on the request }); } 

and adding console.log(postdataChunk); this is not a problem, since all callbacks are properly handled.

In addition, it would be very foolish for me to ask, but do you know console.log (); Does not display in the browser, but in the terminal window?

This may not be the exact answer for you, but I hope this helps a bit.

0
source

Source: https://habr.com/ru/post/1446411/


All Articles