Customsoft
Customsoft

Reputation: 95

POST data from a client javascript page to a node server

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 ("[email protected]"). 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&[email protected]"); 
    }
  };
});

Upvotes: 0

Views: 3817

Answers (2)

Customsoft
Customsoft

Reputation: 95

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

Upvotes: 1

Bassam Rubaye
Bassam Rubaye

Reputation: 302

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&[email protected]"); 

Upvotes: 2

Related Questions