Reactjs 如何在React中从webapi获取响应代码

Reactjs 如何在React中从webapi获取响应代码,reactjs,asp.net-core-webapi,Reactjs,Asp.net Core Webapi,我正在努力学习如何反应。我在web API中创建了一个POST方法,该方法返回一个IActionResult 像这样: [HttpPost] public IActionResult Post(Department model) { try { var query = @"INSERT INTO dbo.Departments

我正在努力学习如何反应。我在web API中创建了一个POST方法,该方法返回一个IActionResult

像这样:

 [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);
            }
        }
这种方法效果很好。但我无法得到回应的“内容”。这就是我在react应用程序中使用此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);
    })
}
通过编辑,我现在能够“提醒”这个=>
函数json(){[native code]}

这是第一个“.then”的结果

在我的警觉中,我得到了“未定义”。如何修复此问题?

我认为您需要“调用”.json(),而不是返回它:

 .then(res => res.json())
而不是:

.then(res => res.json)

你什么意思,先生。我如何填写“报税表”。你能编辑代码让我知道吗?@Ibanez1408刚刚编辑了,如果更清楚的话请告诉我。先生,我确实没有这样做。我刚刚得到
f json(){[native code]}
如果不清楚,请提供一个JSFIDLE,我可以解决问题。非常感谢您,先生。我刚刚从
Response.StatusCode=201更改了我的WebApi;返回内容(“数据已保存”)
返回Ok(“数据已保存”)