繁体   English   中英

在 ReactJS 中使用 Fetch 调用 POST API 时出现错误 415

[英]Error 415 when call POST API using Fetch in ReactJS

我想从 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作战。 您不能针对不同于开发服务器所服务的domain:port API请求。 您在项目中使用Webpack吗? 如果是,最简单的方法是通过Webpack配置来设置API代理。 参见文档 像这样:

// 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'
    },
    // ...
  }
)

不要在主体中使用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);
});

尝试这个

[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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM