【发布时间】:2020-08-17 03:04:54
【问题描述】:
我正在学习如何构建 .NET Core Web api,因此我决定尝试在前端使用 fetch() 向后端发送一个简单的 POST 请求。
前端
const Form = () => {
const submission = {
contactNumber: "123153214",
name: "JJ Lin",
group: 5,
tableId: 3,
isAccompanied: true,
};
const handleSubmit = async (event) => {
event.preventDefault();
fetch("https://localhost:5001/api/guest-submission", {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(submission),
})
.then((response) => {
if (response.status !== 200) {
console.log("not ok" + response.status);
}
})
.catch((err) => {
console.log(err);
});
};
return <button onClick={handleSubmit}>Click here to submit</button>;
};
在后端,我有一个访客类:
public class Guest
{
public string ContactNumber { get; set; }
public string Name { get; set; }
public Group Group { get; set; }
public int TableId { get; set; }
public bool IsAccompanied { get; set; }
}
使用我的控制器:
[HttpPost]
public ActionResult SubmitGuest([FromBody]Guest guestInput)
{
var guest = new Guest
{
ContactNumber = guestInput.ContactNumber,
Name = guestInput.Name,
Group = guestInput.Group,
TableId = guestInput.TableId,
IsAccompanied = guestInput.IsAccompanied
};
Console.WriteLine(guest.Name);
return Ok();
}
使用 Postman 对我有用。但是使用我构建的 react 前端,我一直收到 415 错误。
有人可以启发我吗?谢谢你的帮助!!!
【问题讨论】:
-
尝试将
'Accept': 'application/json'添加到您的标题中,就在 Content-Type 之前
标签: reactjs fetch asp.net-core-webapi