【发布时间】:2019-10-31 18:20:20
【问题描述】:
我正在使用 javascript fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 使用 .net core 3 web api。
控制器返回 OK(object) 但 fetch 收到 500 状态码。
这里是控制器。我可以单步执行代码并查看它是否返回 Ok(customer)
[HttpPost]
public async Task<IActionResult> PostCustomerAsync([FromBody] Customers customer)
{
await _customersService.AddAsync(customer);
return Ok(customer);
}
}
这里是获取。
fetch("./api/customers",
{
method: "POST", body: JSON.stringify(data),
headers: {
'Accept': 'text json',
'Content-Type': 'application/json'
},
})
.then(function(response, error){
console.log(error);
console.log(response);
if(!response.ok){
console.log(response);
throw Error(response.statusText);
}
return response;
}).then(function(response){
Toastr.success(`${data.firstname} ${data.lastname} has been successfully registered`);
const bookChapterTable = new BookChapterTable();
}).catch(function(error){
console.log(error);
Toastr.error(`An error occured : ${error}`);
})
}
获取在 !response.ok 处停止
这是回复。
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 500
statusText: ""
type: "basic"
url: "https://localhost:44300/api/customers"
来自网络标签
Request URL: https://localhost:44300/api/customers
Request Method: POST
Status Code: 500
Remote Address: [::1]:44300
Referrer Policy: no-referrer-when-downgrade
date: Thu, 31 Oct 2019 18:34:14 GMT
server: Microsoft-IIS/10.0
status: 500
x-powered-by: ASP.NET
:authority: localhost:44300
:method: POST
:path: /api/customers
:scheme: https
accept: text json
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 171
【问题讨论】:
-
添加try catch并返回异常来查看问题或只是调试,是
_customersService.AddAsync的问题 -
控制器中没有异常。我可以看到它击中返回 OK(客户)。 fetch 确实有问题。
-
您能否在网络选项卡/提琴手中检查 API 响应状态代码是什么?是否有任何管道从 Web API 抛出 500 错误?
-
将该信息添加到问题中
-
尝试删除
'Accept': 'text json',并尝试使用 Postman
标签: javascript c# .net-core asp.net-core-webapi fetch-api