简体   繁体   中英

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: "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. The API is working if I tested it using Postman like this在此处输入图片说明

在此处输入图片说明

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'
    },
    // ...
  }
)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM