Search code examples
javascriptruby-on-railsjsonrestwebrick

ERROR: bad URI when sending data as JSON with GET method to a Rails resource


Hello I'm performing a GET request on a RESTful Rails resource, like so:

function getGroups(category) { 

  $.ajax({
    type: 'GET',
    url: 'http://localhost:3000/groups.json',
    data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
    success: function(data) {alert(data)},
    contentType: "application/json",
    dataType: 'json'
  });

});

getGroups("own_groups");



The problem is that Webrick server errors out like this:

ERROR bad URI `/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.


It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...



Update: adding code for POST request (where JSON.stringify is required)

function addGroup(name, description) {
  $.ajax({ 
    type: 'POST',
    url:  'http://localhost:3000/groups.json',
    data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
    success: function(data) { alert("ok")},
    contentType: "application/json",
    dataType: 'json'
  });
};

addGroup("nice group", "full of people");

Solution

  • Do not use JSON.stringify. Simply put:

    data: {"access_token":"569669d8df0456", "category":category },
    

    Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json