【发布时间】:2020-06-06 08:57:38
【问题描述】:
所以我不知道为什么我不能从我的 React 应用程序向我的 .NET Core API 发出发布请求。获取请求工作正常。
我的反应代码:
onCreateEmployee = () => {
let empInfo = {
Id: this.refs.Id.value,
Name: this.refs.Name.value,
Location: this.refs.state.value,
Salary: this.refs.Salary.value,
};
fetch("https://localhost:44371/api/Employee", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify(empInfo),
})
.then((r) => r.json())
.then((res) => {
if (res)
this.setState({ message: "New employee is created Successfully" });
});
我的 .NET Core Post 方法:
public bool Post(Employee employee)
{
SqlConnection conn = new SqlConnection(@"server=DESKTOP-D0N7K1B\SQLEXPRESS; database=ReactAppDB; Integrated Security = True");
string query = "insert into EmployeeInfo values(@Id,@Name,@Loc,@Sal)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(new SqlParameter("@Id", employee.Id));
cmd.Parameters.Add(new SqlParameter("@Name", employee.Name));
cmd.Parameters.Add(new SqlParameter("@Loc", employee.Location));
cmd.Parameters.Add(new SqlParameter("@Sal", employee.Salary));
conn.Open();
int noOfRowsAffected = cmd.ExecuteNonQuery();
conn.Close();
return noOfRowsAffected > 0 ? true : false;
}
Cors 已启用并按照成功获取请求的建议工作。 post 方法甚至没有被调用。
谢谢!
【问题讨论】:
标签: .net reactjs api asp.net-core