【问题标题】:Posting to .NET Core WebAPI with ReactJS frontend and fetch api使用 ReactJS 前端发布到 .NET Core WebAPI 并获取 api
【发布时间】: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


【解决方案1】:

我刚刚评论了 mode: "no-cors" 并且它正在工作(我更改了 api url 和提交对象以进行测试)。此外,您正在使用 POST 调用,但在 .then 中,如果状态不是 200,则记录“not ok”;)因为 POST 调用返回 201 以在服务器上成功创建数据。

import React from "react";
const Form = () => {
    const submission = {
        title: 'This is title',
        body: 'This is body',
        userId: 1
    };
    const handleSubmit = async (event) => {
        event.preventDefault();
        fetch("https://jsonplaceholder.typicode.com/posts", {
            method: "POST",
            // mode: "no-cors",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(submission),
        })
        .then((response) => {
            console.log(response, '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>;
};

export default Form

更新:

您需要在启动时启用 CORS。在您的 startup.cs 文件中,在“services.AddControllers();”行之前的 ConfigureServices 函数中添加以下代码

services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost: 3000");
                });
        });  
    }

并在您的启动配置方法中,添加以下代码:app.UseCors();

【讨论】:

  • 感谢@Khabir。当我注释掉 no-cors 时,提交被阻止,因为我的后端在 localhost:5001 而在前端运行 localhost:3000。如何在我的后端将 3000 列入白名单?你知道吗?
  • @aijnij,关注topic,但使用.WithOrigins("http://localhost:{your frontend port here}")
  • @aijnij 我已经添加了您如何允许您的网址的示例。请检查一下
猜你喜欢
  • 1970-01-01
  • 2019-12-03
  • 2020-05-01
  • 1970-01-01
  • 2021-10-11
  • 2021-07-18
  • 2020-12-04
  • 2018-01-02
  • 2013-05-13
相关资源
最近更新 更多