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

10
  • Did you try to enable CORS on your controller ? Can try with any origin to start with, and then define your origin properly : [EnableCors("", "", "*")] Commented Sep 22, 2017 at 3:50
  • @zer0chain I have tried it. It caused another error 500. It also happen in Postman, it returned error 500 Commented Sep 22, 2017 at 3: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? Commented Sep 22, 2017 at 4: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" Commented Sep 22, 2017 at 4:05
  • The error message appears to be clear, the request is cross origin and the server does not respond with CORS headers. Commented Sep 22, 2017 at 4:07

3 Answers 3

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'
    },
    // ...
  }
)
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, the error about CORS is disappeared. But I still got error 415
@Intan Try to add Accept header. I've updated the answer.
still got the same error after I added Accept header
@Intan So it's definitely server side issue. Please update your post to provide request/response headers details, like a developers.google.com/web/tools/chrome-devtools/… . And also give us please actual browser console log after the CORS is gone (is it gone?)
@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/'...
1

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

Comments

-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: "[email protected]",
        name: "Hugh Daniel",
        password: "1234"
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

1 Comment

Removing JSON.stringify doesn't automatically convert the object to string. The invalid text [Object object will be passed instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.