Search code examples
c#reactjshttp-postasp.net-core-webapi

From ReactJS to ASP.NET Core 6.0 HTTP POST method cannot receive data


First of all I am a newbie and I am trying to send HTTP POST request from my ReactJS app to my ASP.NET Core 6 Web API. I get a "400 Bad Request" error.

Here is my post method:

const handleSubmit = async (e) => {
        e.preventDefault();
        try{
            const LoginData = {
                mail: email,
                pwd: password,}
            const res = await fetch(`http://localhost:5122/Login`, {
                method: "post",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(LoginData),
              });
            setEmail('');
            setPassword('');
            setSuccess(true);

I also tried to send post request with axios library but got the same error - "400 Bad request".

And here is my .NET Core POST method:

[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    [Route("/Login")]
    [HttpPost]
    public  ActionResult<ResponseMessage> Login([FromForm] LoginData LoginData)
    {
        // doing some login operations here
    }
}

And LoginData class has two fields:

public class LoginData
{
    public string mail { get; set; }
    public string pwd { get; set; }
}

When I try to send HTTP POST request, I get "404 Bad Request" error. I able to send HTTP GET request.

I am also able to send HTTP POST request without any data.

Can anyone help me please?

Note: I am able to send HTTP POST request with data using x-www-form-urlencoded from Postman.


Solution

  • You are sending the request as json, so I would guess that you endpoints should be denoted as FromBody instead

    public  ActionResult<ResponseMessage> Login([FromBody] LoginData LoginData)
    

    removed misunderstanding by myself