[英]Error 415 when call POST API using Fetch in ReactJS
I want to call an API for register from method in React.我想从 React 中的方法调用一个 API 进行注册。 Below is my javascript code :下面是我的 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);
});
And this is my controller这是我的控制器
[HttpPost]
public ResponseModel RegisterByEmail([FromBody]UserModel user)
{
return _accountService.RegisterEmail(user);
}
But I always get these errors但我总是收到这些错误
I tried to add mode: 'no-cors'
in my javascript code, but it makes Content-Type
set to plain.我试图在我的 javascript 代码中添加mode: 'no-cors'
,但它使Content-Type
设置为普通。 The API is working if I tested it using Postman like this如果我像这样使用 Postman 对其进行测试,则该 API 可以正常工作
You need to combat CORS first of all. 您首先需要与CORS作战。 You can't make API requests against a different domain:port
than the one from which it was served by development server. 您不能针对不同于开发服务器所服务的domain:port
API请求。 Are you using Webpack in your project? 您在项目中使用Webpack吗? If yes, the easiest way is to set up API proxy by the Webpack configuration. 如果是,最简单的方法是通过Webpack配置来设置API代理。 See the doc . 参见文档 。 Something like this: 像这样:
// webpack.config.js
devServer: {
port: 3030,
proxy: {
'/api': {
target: `http://localhost:5001`,
secure: false
}
}
}
Now you have to remove host:port
from fetch
address param and also I would add Accept
header to the request settings: 现在,您必须从fetch
地址参数中删除host:port
,并且还要在请求设置中添加Accept
标头:
fetch('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)
Do not use JSON.stringify
in the body for sending a request and following code will do the work. 不要在主体中使用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);
});
try this尝试这个
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
In js:在js中:
await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Sourse: https://pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller来源: https : //pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.