将表单数据发送到graphql服务器时出现问题



我正在尝试使用axios将表单数据发送到graphql服务器:

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);
})

但我不断地得到";"operations"多部分字段"中的JSON无效;从我的服务器,即使完全相同的";操作";这个物体在邮递员身上很好用。有人知道发生了什么事吗?

您的"json">确实无效。。。

JSON中位于64 位置的意外标记t

这是因为您需要转义反斜杠来转义嵌套的引号。

永远不要手动创建JSON字符串。使用JSON.stringify((代替

const query = 'mutation($file:Upload!){createImage(input:{title: "test", image:$file}) {_id, title, image, pin}}';
data.append("operations", JSON.stringify({ query }));

您通常也不需要手动设置内容类型标头,除非您是从Node后端发出请求。有关详细信息,请参阅此答案。

最新更新