BackPacker777 BackPacker777 - 5 months ago 8
Node.js Question

How do I read Ajax parameter value in Node without framework?

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);

Max Max
Answer

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.

Comments