我正在尝试使用fetch()api发布一些数据,并且我一直收到“400 - Bad Request”错误。 我使用jQuery的$ .ajax()方法没有任何问题,我想知道我做错了什么:
数据
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
使用jQuery(正常工作)
$.ajax({
url: 'http://localhost:3001/api/devices',
type: 'post',
data: obj
}).fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
使用fetch()(不工作)
fetch('http://localhost:3001/api/devices', {
method: 'post',
body: JSON.stringify(obj)
}).then(function(response){
console.log(response)
}).catch(function(error) {
console.log(error)
})
响应
Response {type: "basic", url: "http://localhost:3001/api/devices", redirected: false, status: 400, ok: false…}
我错过了什么吗?
答案 0 :(得分:0)
以下是使用fetch API的方法:
namespace WebApi.Controllers
{
public class obj
{
public int id_user { get; set; }
public int id_category { get; set; }
public string note { get; set; }
}
public class devicesController : ApiController
{
public string Post([FromBody]obj value)
{
//use newtonsoft json
string json = JsonConvert.SerializeObject(value);
return json;
}
}
}
查看:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#callAjax").click(function () {
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
//this worked for me, FYI, I USE different port than you
//$.ajax({
// url: 'http://localhost:53110/api/devices',
// type: 'post',
// data: obj
//}).done(function (data, textStatus, jqXHR) {
// alert(data);
//}).fail(function (xhr, status, errorThrown) {
// alert("Sorry, there was a problem!");
// console.log("Error: " + errorThrown);
// console.log("Status: " + status);
// console.dir(xhr);
//})
//https://davidwalsh.name/fetch - does not work in ie11
//https://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc
fetch('http://localhost:53110/api/devices', {
//I HAD TO add this headers because 415 unsupported media type
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(obj)
}).then(function (response) {
//alert(response)
//ADDED THIS https://developers.google.com/web/updates/2015/03/introduction-to-fetch
response.json().then(function (data) {
alert(data);
});
}).catch(function (error) {
alert(error)
})
})
})
</script>
</head>
<body>
<div>
<input type="button" value="callAjax" id="callAjax" />
</div>
</body>
</html>