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.
答案 0 :(得分:2)
很棒,你能找到你的错误。 这可能是由于一些JSON解析错误引起的,因为粗略查询包含字符串化的JSON。
将来,为了提出更简单的请求,您可以将查询和变量作为单独的字段发送:
var mutation = `
mutation MyMutation($input: AddPositionInput!) {
addPosition(input: $input) {
result {
name
}
}
}
`;
...
$.ajax({
...
data: JSON.stringify({
query: mutation,
variables: {
input: {
name: {
p: "Develo",
},
},
},
}),
...
});