javascript - .net core web api post使用fetch出现500错误
问题描述
我正在使用 带有.net core 3 web api的javascript fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 。
控制器返回 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
解决方案
我有同样的问题。显示错误,因为我没有在标头发送“X-XSRF-Token”(它可以是“X-CSRF-TOKEN”,取决于系统)。如果有人有同样的问题,请确保您在标题处传递它。
fetch(signUpEmailUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRF-Token': gettoken()
},
credentials: 'include',
body: JSON.stringify({
email: $('#sign_up_email').val(),
firstName: $('#first_name').val(),
lastName: $('#last_name').val(),
token: $('#sign_up_token').val()
})
})
.then(res => (res.json()))
.then(data => {
console.log(data);
loginSuccess(data);
})
.catch(err => {
console.log(err);
});
推荐阅读
- ios - Nativescript Greensock 问题 - 未找到模块:错误:无法解析“TweenLite”
- python - 如何将值从 Pyqt5 GUI 传递给多个进程
- android - 是否可以为 Flutter 的可访问性焦点系统强制平滑隐式滚动?
- c# - 带有命令的 FTP 到大型机数据集
- c# - XDocument xml 已解析,但未能保存属性。xml.linq
- c - 尝试做一些 c 编程作业,需要一些指导
- sql - SQL Server:JSON 审计
- windows - Windows RIO 套接字是否注意接收端的 TCP PSH 标志?
- mysql - 使用 jdbc 在 docker 中连接 mysql 时遇到问题
- angular - 无法使用“npm 脚本”部署 firebase?