“TypeError: Failed to fetch” when the request hasn’t actually failed Error

Viewed 57

I'm using an API to make my login page validate the user and password with this code:

function ola() {

var myHeaders = new Headers();

myHeaders.append("Content-Type", "text/plain");


//WITH USERNAME AND PASSWORD LIKE THIS VVVVVV
var raw = "{\r\n  \"password\": \"Olasou1!\",\r\n  \"username\": \"bernardo\"\r\n}\r\n";



var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://api.secureme.pt/api/v1/auth/login", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

};

I get a success message so I know that it worked

But when I try to use the user inputs on the variable raw like this:

function ola() {
  var user = document.getElementById("user").value;
  var password = document.getElementById("password").value;

  var myHeaders = new Headers();
  myHeaders.append("Content-Type", "text/plain");
  


  var raw = {
      password: password,
      username: user
  };
  


  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
  };
  
  fetch("https://api.secureme.pt/api/v1/auth/login", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

};

And when I put the same username and password, I get an error saying that it failed to fetch:

error TypeError: Failed to fetch
    at ola (:5500/js/loginRegister.js:36:3)
    at HTMLButtonElement.onclick (loginRegister.html:22:74)

I can't figure out why, can someone help me with this?

This is where I call the function on html file:

<button type="submit" class="submit-btn" onclick="ola()">Log In</button>
1 Answers
Related