0

I am trying to pass a variable to my Ajax send and read it in Node without using a framework. I am not trying to return the value back to the DOM, I just need to read the value passed to Node.js. Here is what I have:

Ajax:

const XHR = new XMLHttpRequest();
XHR.open('POST', document.url, true);
XHR.setRequestHeader('X-Requested-load', 'XMLHttpRequest2');
XHR.send(`password=${password}`);

Nodejs:

const QS = require('querystring');
let password = QS.parse(req.body);
req.on('data', (data) => {
     password = QS.parse(data);
});
console.log(password);
BackPacker777
  • 673
  • 2
  • 6
  • 21
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Jun 06 '16 at 13:33
  • @Juhana - Unless I'm missing something, I don't think this is a duplicate of that other question.... – BackPacker777 Jun 06 '16 at 13:45
  • 2
    Yes it is. `req.on()` is asynchronous. – JJJ Jun 06 '16 at 13:48
  • @Juhana - I'm not trying to read the response in the DOM, just the request in Nodejs. – BackPacker777 Jun 06 '16 at 14:06
  • Yes, that's right. And the method you're using to read the request in Node is asynchronous. – JJJ Jun 06 '16 at 14:24

2 Answers2

0

Hope this will help you:

http.createServer(function (request, response) {
  if (request.method == 'POST') {
    // save all data received
    var postdata = '';

    // receiving data
    request.on('data', function(chunk) {
        postdata += chunk;                                                                 
        // Avoid too much POST data                                                        
        if (postdata.length > 1e6)
            request.connection.destroy();
    });

    // received all data
    request.on('end', function() {
        var post = qs.parse(postdata);
        // handle post by accessing
        // post['password']
        // response.send(process(post['password']));
    });
  } else {
    console.log("Non POST request received at " + request.url);
  }
}).listen();

In your example you are trying to access password out of the callback where this data is provided.

Max
  • 1,824
  • 13
  • 22
0
const QS = require('querystring');
let password = QS.parse(req.body);
req.on('data', (data) => {
 password = QS.parse(data);
 //async. access data here
 console.log(password);
});
pbordeaux
  • 425
  • 1
  • 5
  • 18