【发布时间】:2020-08-26 20:07:04
【问题描述】:
我正在尝试学习 React。我在我的 Web API 中创建了一个返回 IActionResult 的 POST 方法
像这样:
[HttpPost]
public IActionResult Post(Department model)
{
try
{
var query = @"INSERT INTO dbo.Departments
(DepartmentName)
VALUES (@departmentName)
";
int result = 0;
using (var con = new SqlConnection(ConnectionString))
{
con.Open();
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@departmentName", SqlDbType.VarChar).Value = model.DepartmentName;
cmd.CommandType = CommandType.Text;
result = cmd.ExecuteNonQuery();
}
}
Response.StatusCode = 201;
return Content("Data has been saved");
}
catch (Exception ex)
{
Response.StatusCode = 400;
return Content(ex.Message);
}
}
这个方法很好用。但我无法获得响应的“内容”。这就是我在我的反应应用程序中使用这个 API 的方式
handleSubmit(event) {
event.preventDefault();
fetch('http://localhost:1173/api/Department', {
method: 'POST',
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
DepartmentId: 0,
DepartmentName: event.target.departmentName.value
})
})
.then(res => res.json)
.then((result) => {
console.log(result);
alert(result);
},
(error) => {
alert('Failed in adding data: ' +error);
})
}
通过我的编辑,我现在可以“提醒”这个 => function json() { [native code] }
这是第一个“.then”的结果
并且在我的警报下,我得到“未定义”。我该如何解决这个问题?
【问题讨论】:
标签: reactjs asp.net-core-webapi