Home > Software engineering >  ReactJS is throwing an error when catching a response from .NET API
ReactJS is throwing an error when catching a response from .NET API

Time:12-21

I am connecting my ReactJS web app to my .NET Api and I am receiving an error whenever REACTJS is receiving the response from the API.

Here is what the error is saying enter image description here

The api is returning a STRING which is the JWT token. Here is the code for that particular task:

  public IActionResult Login([FromBody] UserLogin userLogin)
        {
            var user = Authenticate(userLogin);

 
            if (user != null)
            {
                var token = Generate(user);
                return Ok(token);
            }
            else
            {
                return NotFound("User not found");
            }
        }

and here is the fetch method in REACTJS that is responsible for this task:

  function getJWTToken(event) {
    event.preventDefault();

    const userCredentials = {
      email: user_email,
      password: user_password,
    };

    const url = Constants.API_URL_LOGIN;

    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(userCredentials),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("Success:", data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }

I spent two hours already but I cannot figure out what to do in here since this is my first project using react and .net. Thank you for your help.

CodePudding user response:

Since you are not receiving json but plain text, use response.text() to read the response

CodePudding user response:

I solved my propblem now. Thank you to Stutje, he gave me the idea. Instead of using response.json() , response.text() worked.

  • Related