Search code examples
javascriptnode.jsjsonxmlhttprequest

XMLHttpRequest() sends emtpy payload


I'm having issue with site. I need to use XMLHttpRequest to send GET request to my api running on Node.js The Issue is that when I do the request it doesn't send the payload. It's just an empty object. If I do the same without the XMLHttpRequest, for example in Postman everything works.

This is my XMLHttpRequest Function:

// AJAX Client (for RESTful API)
app.client = {}

// Interface for making API calls
app.client.request = function(headers,path,method,queryStringObject,payload,callback){

  // Set defaults
  headers = typeof(headers) == 'object' && headers !== null ? headers : {};
  path = typeof(path) == 'string' ? path : '/';
  method = typeof(method) == 'string' && ['POST','GET','PUT','DELETE'].indexOf(method.toUpperCase()) > -1 ? method.toUpperCase() : 'GET';
  queryStringObject = typeof(queryStringObject) == 'object' && queryStringObject !== null ? queryStringObject : {};
  payload = typeof(payload) == 'object' && payload !== null ? payload : {};
  callback = typeof(callback) == 'function' ? callback : false;

  // For each query string parameter sent, add it to the path
  var requestUrl = path+'?';
  var counter = 0;
  for(var queryKey in queryStringObject){
     if(queryStringObject.hasOwnProperty(queryKey)){
       counter++;
       // If at least one query string parameter has already been added, preprend new ones with an ampersand
       if(counter > 1){
         requestUrl+='&';
       }
       // Add the key and value
       requestUrl+=queryKey+'='+queryStringObject[queryKey];
     }
  }

  // Form the http request as a JSON type
  var xhr = new XMLHttpRequest();
  xhr.open(method, requestUrl, true);
  xhr.setRequestHeader("Content-type", "application/json");

  // For each header sent, add it to the request
  for(var headerKey in headers){
     if(headers.hasOwnProperty(headerKey)){
       xhr.setRequestHeader(headerKey, headers[headerKey]);
     }
  }

  // If there is a current session token set, add that as a header
  if(app.config.sessionToken){
    xhr.setRequestHeader("token", app.config.sessionToken.id);
  }

  // When the request comes back, handle the response
  xhr.onreadystatechange = function() {
      if(xhr.readyState == XMLHttpRequest.DONE) {
        var statusCode = xhr.status;
        var responseReturned = xhr.responseText;

        // Callback if requested
        if(callback){
          try{
            var parsedResponse = JSON.parse(responseReturned);
            callback(statusCode,parsedResponse);
          } catch(e){
            callback(statusCode,false);
          }

        }
      }
  }

  // Send the payload as JSON
  var payloadString = JSON.stringify(payload);
  xhr.send(payloadString);

};

This is code from when I make the request:

app.loadCartViewPage = function(){
  var emailAdress = typeof(app.config.sessionToken.emailAdress) == 'string' ? app.config.sessionToken.emailAdress : false;
  if(emailAdress){
    var queryStringObject = { 'emailAdress' : emailAdress };
    app.client.request(undefined, 'api/users', 'GET', queryStringObject, undefined, function(statusCode, responsePayload){
      if(statusCode == 200){
        var cartId = typeof(responsePayload.carts) == 'object' && responsePayload.carts instanceof Array ? responsePayload.carts[0] : [];
        var payload = {'emailAdress' : emailAdress, 'cartId' : cartId };
        app.client.request(undefined, 'api/carts', 'GET', undefined, payload, function(statusCode, responsePayload){
          console.log(responsePayload);
        });
      } else {
        app.logUserOut();
      }
    });
  } else {
    app.logUserOut();
  }
};

The first GET request goes through as it should where I pass only queryString, but the second sends just empty objects.

Image

Thanks for help in advance


Solution

  • XMLHttpRequest does not send a body for a GET or HEAD request. Arguments or options for those requests should be in query parameters, not in the body.

    Here's a note from the MDN page on .send():

    send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.