Reputation: 143
I want to call an API for register from method in React. Below is my javascript code :
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: "[email protected]",
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);
}
I tried to add mode: 'no-cors'
in my javascript code, but it makes Content-Type
set to plain.
The API is working if I tested it using Postman like this
Upvotes: 2
Views: 14544
Reputation: 11
try this
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
In 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
Upvotes: 1
Reputation: 20744
You need to combat CORS first of all. You can't make API requests against a different domain:port
than the one from which it was served by development server. Are you using Webpack in your project? If yes, the easiest way is to set up API proxy by the Webpack configuration. 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('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)
Upvotes: 4
Reputation: 5126
Do not use JSON.stringify
in the body for sending a request and following code will do the work.
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
email: "[email protected]",
name: "Hugh Daniel",
password: "1234"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Upvotes: -1