I am trying to send form data to a graphql server using axios:
let data = new FormData();
let img = {}
img.file = e.target.files[0];
data.append('operations', '{ "query" : "mutation($file:Upload!){createImage(input:{title: \"test\", image:$file}) {_id, title, image, pin}}"}');
data.append('map', {"0":["variables.file"]})
data.append('0', img);
axios({
method: "post",
url: "http://localhost:8000/pin/62310a56ca26b64f107de717/image/",
data: data,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (res) {
console.log(res)
})
.catch(function(err){
console.error(err);
})
but I keep getting "Invalid JSON in the ‘operations’ multipart field" from my server even though the very same "operation" object works fine in postman. Anybody know what's going on?
CodePudding user response:
Your "json" is indeed invalid...
Unexpected token t in JSON at position 64
This is because you would have needed to escape the backslashes to escape the nested quotes.
Never manually create JSON strings. Use JSON.stringify() instead
const query = 'mutation($file:Upload!){createImage(input:{title: "test", image:$file}) {_id, title, image, pin}}';
data.append("operations", JSON.stringify({ query }));
You also generally don't need to manually set content-type headers unless you're making the request from a Node backend. See this answer for more details on that.