我有这个遗留的 C# 代码(我不懂 C#),我需要用 Javascript 编写相同的功能(我非常了解 JS)。所以 C# 代码是:
static JavaScriptSerializer serializer = new JavaScriptSerializer();
MultipartFormDataContent content = new MultipartFormDataContent();
item item_1 = new item
{
a = 'a',
b = 'b'
};
string jsonPayload = serializer.Serialize(item_1);
var stringContent = new StringContent(jsonPayload);
stringContent.Headers.ContentType.MediaType = "text/json";
content.Add(stringContent, item_1.GetType().Name);
// then it makes a network request
如果我必须做出最好的猜测,这就是我认为它会在 JS 中做的事情,尽管我一定有点偏离,因为 api 正在返回 415 Unsupported Media Type:
const item_1 = {
a: 'a',
b: 'b'
};
const jsonPayload = JSON.stringify(item_1);
const formData = new FormData();
formData.set('data', jsonPayload);
fetch('/some_api/endpoint',{
headers: {
"Content-Type":"text/json"
},
method: 'POST',
body: formData
});
如果您需要更多信息,或者对如何改进帖子有任何疑问或建议,请发表评论!感谢您的帮助!
最佳答案
为什么要创建 FormData 对象?我认为您只想将内容作为 JSON 发送;
const item_1 = {
a: 'a',
b: 'b'
};
const jsonPayload = JSON.stringify(item_1);
fetch('/some_api/endpoint',{
headers: {
"Content-Type":"text/json"
},
method: 'POST',
body: jsonPayload
});
从这个文档页面 (https://developer.mozilla.org/en-US/docs/Web/API/FormData) 看来,这不是 JSON 内容类型;
It uses the same format a form would use if the encoding type were set to "multipart/form-data".
关于javascript - C# 到 Javascript : What the equivalent of `new MultipartFormDataContent();` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860114/