Search code examples
javascriptjsonajaxgithubxmlhttprequest

Problems parsing JSON -- ajax request sending as application/x-www-form-urlencoded


I am trying to connect to the github api using javascript. I have a generic github function that does a call to a github uri.

function githubRequest(endpoint, method, body) {
  // console.log(github_token);
  var baseUri = "https://api.github.com";
  var fullUri = baseUri + endpoint; // endpoint is like /repos/username/repo/contents/path
  // set up the request
  $.ajax({
    url: fullUri,
    type: method,
    beforeSend: function(request) {
      request.setRequestHeader("Authorization", "Bearer " + github_token);
      request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    },
    data: body,
    success: function(data) {
      console.log("SUCCESS");
      alert("Filed added");
    },
    error: function(data) {
      console.log("ERROR");
      alert("Something went wrong ... check console");
    }
  });
}

github_token is defined in another file.

Right now I am testing this using a PUT method, and I am trying to create a file on my repo.

More info here under the "Create a file" section: https://developer.github.com/v3/repos/contents/

Here is the body that I send along.

{
    "message": "Added files",
    "committer": {
        "name": name,
        "email": email
    },
    "content": base_64_content
}

Then I call my function. I try to upload a README.md file as an example.

In my console for chrome, I see two requests (I assume one is the preflight one and one is the actual one). The preflight one succeeds, the second one doesn't.

enter image description here

For some reason in the second request, the request payload is as follows:

message=Added+files&committer%5Bname%5D=John+Doe&committer%5Bemail%5D=johndoe%40gmail.com&content=base64Content%3D, where base64Content is the actual base 64 content.

I have two questions then.

Firstly, if the preflight request succeded, why did this one fail? Secondly, why is it sending as non-json. Github response is

documentation_url:"https://developer.github.com/v3/repos/contents/#update-a-file"
message:"Problems parsing JSON"

Solution

  • It is expecting body to be stringified, because it can't send an object in an ajax request.

    data: JSON.stringify(body) instead of data: body

    The pre-flight check probably works because the structure of the message is ok, but when it tries to parse the json it fails.