2

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: "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 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

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
Intan
  • 143
  • 1
  • 2
  • 15
  • Did you try to enable CORS on your controller ? Can try with any origin to start with, and then define your origin properly : [EnableCors("*", "*", "*")] – zer0chain Sep 22 '17 at 03:50
  • @zer0chain I have tried it. It caused another error 500. It also happen in Postman, it returned error 500 – Intan Sep 22 '17 at 03:56
  • Why do you `POST` to `"http://localhost:5001/api/Account"` from `"http://localhost:3030"`? Can you include actual text of error messages at Question? – guest271314 Sep 22 '17 at 04:02
  • @guest271314 I created a front end for my apps using React in `"http://localhost:3030"`. And call REST API (created using .Net) in `"http://localhost:5001/api/Account"` – Intan Sep 22 '17 at 04:05
  • The error message appears to be clear, the request is cross origin and the server does not respond with CORS headers. – guest271314 Sep 22 '17 at 04:07
  • @Intan what is the content of the 500 you got ? Obviously the preflight failed because cors is not set properly on server, so you can to configure it or to disable it. – zer0chain Sep 22 '17 at 04:24
  • The cause of the problem you’re seeing is, the server for that `http://localhost:5001/api/Account` endpoint you’re making the request to is responding to an `OPTIONS` request with a `415 Unsupported Media` HTTP status code. It makes zero sense for a server to do that, & it pretty much indicates the server’s broken. Because the thing is, the `OPTIONS` request it’s responding to that way is a CORS preflight request your browser automatically on its own is sending to the server. And the browser doesn’t include any Content-Type header in that `OPTIONS` request. So the request has no media type. – sideshowbarker Sep 22 '17 at 06:57
  • To be clear: a properly-configured server should never be looking for a media type in an `OPTIONS` request; the server shouldn’t care if the `OPTIONS` request has no a Content-Type header, but it also shouldn’t care if it does have one. That’s because `OPTIONS` requests have no payload (request body) — just like `HEAD` requests have no payload. So the server doesn’t need a Content-Type in the request in order to respond to it; the request Content-Type is completely irrelevant for `OPTIONS`, so a server should never be responding to an `OPTIONS` request with a 415 – sideshowbarker Sep 22 '17 at 07:04
  • i just add answer here see [link](https://stackoverflow.com/questions/44192731/fetch-post-is-returning-http-415-while-curl-goes-on-fine-and-returns-result/62728896#62728896) – Samir Ghoneim Jul 04 '20 at 12:09
  • i just answered the same question [here](https://stackoverflow.com/questions/44192731/fetch-post-is-returning-http-415-while-curl-goes-on-fine-and-returns-result/62728896#62728896) – Samir Ghoneim Jul 04 '20 at 12:10

3 Answers3

4

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'
    },
    // ...
  }
)
dhilt
  • 18,707
  • 8
  • 70
  • 85
  • Yes, the error about CORS is disappeared. But I still got error 415 – Intan Sep 22 '17 at 05:28
  • @Intan Try to add Accept header. I've updated the answer. – dhilt Sep 22 '17 at 05:38
  • still got the same error after I added Accept header – Intan Sep 22 '17 at 05:45
  • @Intan So it's definitely server side issue. Please update your post to provide request/response headers details, like a https://developers.google.com/web/tools/chrome-devtools/network-performance/imgs/headers.svg . And also give us please actual browser console log after the CORS is gone (is it gone?) – dhilt Sep 22 '17 at 07:52
  • @Intan I made another one update to clarify the fetch request url param. After you set up proxy for dev server (if you really did it), you need to make api requests from the same `host:post` as the dev server (3030). In that case you may (even should) not to specify `host:port` in the address param, just `fetch('/api/Account/'...` – dhilt Sep 22 '17 at 08:07
0

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

-1

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: "hugh.daniel@gmail.com",
        name: "Hugh Daniel",
        password: "1234"
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
  • Removing `JSON.stringify` doesn't automatically convert the object to string. The invalid text `[Object object` will be passed instead. – Ruxo Jul 17 '21 at 08:17