使用 JQuery 将 JSON 数据发布到 API 时不支持的媒体类型
Unsupported Media Type when Posting JSON data to API using JQuery
我正在使用 JQuery 3 将数据发布到 API,如下所示:
$.post({ url: "api/questions", data: { content: "Content" }, dataType: "json" })
.done(function (data, status, xhr) {
console.log(message);
})
.fail(function (xhr, status, error) {
console.log(error);
})
当我 运行 它时,我得到以下错误:
Unsupported Media Type
我不确定为什么会这样。我使用 PostMan 测试了我的 API 以发送具有以下正文的 Post 请求:
{
content: "Content"
}
它运行良好......我错过了什么?
试试这个:
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': url,
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};
(摘自 this 答案)
我正在使用 JQuery 3 将数据发布到 API,如下所示:
$.post({ url: "api/questions", data: { content: "Content" }, dataType: "json" })
.done(function (data, status, xhr) {
console.log(message);
})
.fail(function (xhr, status, error) {
console.log(error);
})
当我 运行 它时,我得到以下错误:
Unsupported Media Type
我不确定为什么会这样。我使用 PostMan 测试了我的 API 以发送具有以下正文的 Post 请求:
{
content: "Content"
}
它运行良好......我错过了什么?
试试这个:
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': url,
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};
(摘自 this 答案)