【问题标题】:How to get the reponse code from Web API in React如何在 React 中从 Web API 获取响应代码
【发布时间】: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


    【解决方案1】:

    我相信你需要“调用” .json() 而不是返回它:

     .then(res => res.json())
    

    代替:

    .then(res => res.json)
    

    【讨论】:

    • 您是什么意思,先生。我如何输入“返回”。你能编辑一下代码让我知道吗?
    • @Ibanez1408 刚刚做了,让我知道是否更清楚?
    • 我确实做到了,先生。我刚收到f json() { [native code] }
    • 如果不清楚请提供 JSFiddle 我可以解决问题
    • 非常感谢先生。我刚刚将我的 WebApi 从 Response.StatusCode = 201; return Content("Data has been saved"); 更改为 return Ok("Data has been saved")
    猜你喜欢
    • 2022-08-19
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多