0

Is it possible to POST data from a client javascript page to a node server (server.js) using an AJAX XMLHttpRequest()? What I am looking for is javascript code that will receive the data on the node server, specifically the values for member_nm ("newName") and member_email ("mail@google.com"). I control the server. I also understand that I can also use GET to send the text values by means of a querystring. Below is the request that is sent from the client javascript page by means of an event handler:

document.getElementById("btnAddMember").addEventListener("click", function()
{
  var request = new XMLHttpRequest();
  var path = "/Users/Admin/WebstormProjects/projectName/server.js";
  request.onreadystatechange = function()
  {
    if ( request.readyState === 4 && request.status == 200 )
    {
      request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
      request.open("POST", path, true);
      request.send("member_nm=newName&member_email=mail@google.com"); 
    }
  };
});
Customsoft
  • 95
  • 3
  • 12
  • possible duplicate of http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest ? – crackmigg Mar 16 '16 at 17:38
  • or duplicate of http://stackoverflow.com/questions/12006417/nodejs-server-that-accepts-post-requests ? – crackmigg Mar 16 '16 at 17:42
  • The first 'possible duplicate' asks how to formulate an XMLHttpRequest which is not my question. The code that I have included answers the question asked in the 'possible duplicate', it does not supply me with an answer. – Customsoft Mar 16 '16 at 18:13
  • The second 'duplicate' does include a solution if using node with express (which I am). I will have a look at it. Thanks... – Customsoft Mar 16 '16 at 18:17
  • The "possible duplicate" is nothing personal, just a way for you to get a good answer very fast. – crackmigg Mar 16 '16 at 18:52
  • Understood. Appreciate the input... – Customsoft Mar 17 '16 at 19:16

2 Answers2

2

You need to setup your server to accept this post request, the easiest will be to use Express with bodyParser middleware, like this :

var express = require('express');
var    server=express();
var    bodyParser= require('body-parser'); 

server.use(bodyParser.json());

server.post('/', function(req, res){
  if(req.body){
   // get the params from req.body.paramName
}
});

server.listen(8222, function(){
  console.log('listening for requests ..')
});

In your client code change the 'path' to point to the server url:port, and I will put these outside of the onReadyStateChange:

request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
  request.open("POST", path, true);
  request.send("member_nm=newName&member_email=mail@google.com"); 
Bassam Rubaye
  • 302
  • 1
  • 4
1

This is a working solution on how to POST variables from a client javascript file to a Node server using Express. The POST is initiated on the client by means of an event handler, btnAddMember. txtName.value and txtMembershipType.value contain the values to be posted. Note the syntax that is necessary to parse the values correctly. member_nm and member_type will be used to reference the properties on the Node server. First the client javascript:

document.getElementById("btnAddMember").addEventListener("click", function()
{
  var request = new XMLHttpRequest();
  var path = "http://0.0.0.0:0000"; // enter your server ip and port number
  request.open("POST", path, true); // true = asynchronous
  request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
  var text= '{"member_nm":"' + txtName.value + '","member_type":"' + txtMembershipType.value + '"}';
  request.send ( text );
});

Next is the server side code. Note that bodyParser must now be added to your project as a node_module. This can be done through the node program manager (npm). The POST statement basically parses the req.body from a JSON format to a javascript object format using a variable called 'member'. The code then logs the posted values for the two variables, member_nm and member_type. Finally a response status is sent to the client if the POST is successful.

var bodyParser = require("body-parser");
...
app.use(bodyParser.text({ type: "application/json" }));
...
// receive the POST from the client javascript file
app.post("/", function (req, res)
{
  if (req.body)
  {
    var member = JSON.parse( req.body ); // parse req.body as an object
    console.log("member_nm: " + member.member_nm );
    console.log("member_type: " + member.member_type );
    res.sendStatus(200); // success status
  }
  else
  {
    res.sendStatus(400); // error status
  }
});  
Customsoft
  • 95
  • 3
  • 12