简体   繁体   中英

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.

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",
        },
      },
    },
  }),
  ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM