Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST on GraphQL returns 400 BAD REQUEST

I want to POST a mutation that updates field "name" which is JSONString. When I do that, I got a response - 400 BAD REQUEST, but when I try other mutation (with the field type of String) it goes smooth and the result is exactly what I want.

function updateUserData() {
    var xhr = new XMLHttpRequest(),
        token = "BTNsngsfgfstnrw64wNsrgnws"

    var mutation = `mutation {
        addPosition( input: {
            name: "{\"pl\": \"Devlo\"}"
        }) {
            result {
                name
            }
        }
    }`;

$.ajax({
    beforeSend: (xhr) => xhr.setRequestHeader('Authorization', 'Basic ' + token),
    type: 'POST',
    url: 'http://46.17.113.45/graphql',
    data: JSON.stringify({ 'query': 'mutation { addPosition( input: { name: "{\\"p\\": \\"Develo\\"}" }) { result { name 
    contentType: 'application/json'
    }).done(function(response) {
        console.log(response)
});}

In GraphiQL that mutation works well. Returned value is what exactly what's in the query. Is there a problem with JSONString and those quotes, or problem is somewhere else? The token, type, contentType is good - other POSTs with a query, or mutations works well. I already spend a couple of hours trying to make this work, but no effects.

Solution I got it. There should be double slashes before quotes instead of one.

like image 312
Shenloc Avatar asked Jun 27 '17 07:06

Shenloc


1 Answers

Great you were able to find your error. This was likely caused by some JSON parsing error, due to the sketchy query containing stringified JSON.

In the future, and to make easier requests, you can send your query and your variables as separate fields:

var mutation = `
  mutation MyMutation($input: AddPositionInput!) {
    addPosition(input: $input) {
      result {
          name
      }
    }
  }
`;

...

$.ajax({
  ...
  data: JSON.stringify({
    query: mutation,
    variables: {
      input: {
        name: {
          p: "Develo",
        },
      },
    },
  }),
  ...
});
like image 92
yachaka Avatar answered Oct 26 '22 19:10

yachaka