【问题标题】:Error 415 when call POST API using Fetch in ReactJS在 ReactJS 中使用 Fetch 调用 POST API 时出现错误 415
【发布时间】:2017-09-22 03:35:41
【问题描述】:

我想从 React 中的方法调用一个 API 进行注册。下面是我的 javascript 代码:

     fetch('http://localhost:5001/api/Account', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            email: "hugh.daniel@gmail.com",
            name: "Hugh Daniel",
            password: "1234"
        })
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

这是我的控制器

    [HttpPost]
    public ResponseModel RegisterByEmail([FromBody]UserModel user)
    {
        return _accountService.RegisterEmail(user);
    }

但我总是遇到这些错误

我尝试在我的 javascript 代码中添加 mode: 'no-cors',但它使 Content-Type 设置为普通。 如果我像这样使用 Postman 测试它,API 就可以工作

【问题讨论】:

  • 您是否尝试在您的控制器上启用 CORS?可以尝试从任何来源开始,然后正确定义您的来源:[EnableCors("", "", "*")]
  • @zer0chain 我试过了。它导致另一个错误 500。它也发生在 Postman 中,它返回错误 500
  • 你为什么从"http://localhost:3030"POST 到"http://localhost:5001/api/Account"?您能否在问题中包含错误消息的实际文本?
  • @guest271314 我在"http://localhost:3030" 中使用 React 为我的应用程序创建了一个前端。并在"http://localhost:5001/api/Account"中调用REST API(使用.Net创建)
  • 错误信息看起来很清楚,请求是跨域的,服务器没有响应 CORS 标头。

标签: javascript reactjs fetch


【解决方案1】:

首先你需要对抗 CORS。您不能针对与开发服务器提供服务的domain:port 不同的 API 请求。你在你的项目中使用 Webpack 吗?如果是,最简单的方法是通过 Webpack 配置设置 API 代理。 See the doc。像这样的:

// webpack.config.js
devServer: {
    port: 3030,
    proxy: {
      '/api': {
        target: `http://localhost:5001`,
        secure: false
      }
    }
  }

现在您必须从fetch 地址参数中删除host:port,并且我还要在请求设置中添加Accept 标头:

fetch('/api/Account', {
    method: 'post',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    // ...
  }
)

【讨论】:

  • 是的,关于CORS的错误消失了。但我仍然收到错误 415
  • @Intan 尝试添加 Accept 标头。我已经更新了答案。
  • 添加 Accept 标头后仍然出现同样的错误
  • @Intan 所以这绝对是服务器端的问题。请更新您的帖子以提供请求/响应标头详细信息,例如 developers.google.com/web/tools/chrome-devtools/… 。并且请在 CORS 消失后给我们实际的浏览器控制台日志(它消失了吗?)
  • @Intan 我进行了另一项更新以阐明获取请求 url 参数。为开发服务器设置代理后(如果您真的这样做了),您需要从与开发服务器 (3030) 相同的host:post 发出 api 请求。在这种情况下,您可能(甚至应该)不在地址参数中指定 host:port,只需 fetch('/api/Account/'...
【解决方案2】:

试试这个

[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]        
public class TestController : ControllerBase
{}

在js中:

await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });

来源:https://pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller

【讨论】:

    【解决方案3】:

    不要在正文中使用JSON.stringify 来发送请求,下面的代码将完成这项工作。

    fetch('http://localhost:5001/api/Account', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: {
            email: "hugh.daniel@gmail.com",
            name: "Hugh Daniel",
            password: "1234"
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
    

    【讨论】:

    • 删除 JSON.stringify 不会自动将对象转换为字符串。将改为传递无效文本 [Object object。
    猜你喜欢
    • 2020-09-30
    • 2020-11-19
    • 2021-09-22
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2019-05-27
    • 2020-10-08
    相关资源
    最近更新 更多