Intan
Intan

Reputation: 143

Error 415 when call POST API using Fetch in ReactJS

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);
    }

But I always get these errors enter image description here

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 enter image description here

enter image description here

Upvotes: 2

Views: 14544

Answers (3)

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

dhilt
dhilt

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

Vaibhav Mule
Vaibhav Mule

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

Related Questions