0

I am making use of Fetch API to make a network request and get a response back which includes the session token details.

Below is the piece of code I am using in Apache Tomcat server.

   <!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <title>My App</title>
    <link href="login.css" rel="stylesheet">
  </head>
  <body class="text-center">
    <main class="form-signin">
    <!-- <form onsubmit="return login()"> -->
    <form>
       <!-- <img class="mb-4" src="./logo.png" alt="" height="300"> -->
        <h1 class="h3 mb-3 fw-normal"><b>My App</b> - Login</h1>
    
        <div class="form-floating">
          <input type="text" class="form-control" id="username" placeholder="test@example.com">
          <label for="floatingInput">Email address</label>
        </div>
        <div class="form-floating">
          <input type="password" class="form-control" id="password" placeholder="Password">
          <label for="floatingPassword">Password</label>
        </div>
    
        
        <button class="w-100 btn btn-lg btn-primary mt-3" type="submit" onClick=clickLogin()>Login</button>
        
        <div id="myData"></div>

      </form>
    </main>

    <!--<script src="login.js"></script>    -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    <script>
    async function clickLogin() {
        console.log("Inside click Login");
  //e.preventDefault();
  const response = await fetch ('https://example.com/authenticate', 
  {
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
       'Username': 'demo@exk.com',
       'Password': 'Ch4ng3it!'
    },
})
  /*.then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log('Request Failed', err))*/
  
    console.log("Reached before ok");
  
   if (!response.ok) {
      throw new Error(`Error! status: ${response.status}`);
    }
    
    const result = await response.json();
    
    console.log(result);
    
    
  
  document.getElementById(myData).innerHTML = result;
}


    </script>
  </body>
</html>

enter image description here

The above image shows the network trace. The call to authenticate endpoint is cancelled everytime.

I am not sure what I am doing wrong here. Also, I added the URL app.example.com in CORS for resource server API.

After making the suggested changes, below is snippet of code.

   <!doctype html>
    <html lang="en">
      <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    
        <title>My App</title>
        <link href="login.css" rel="stylesheet">
      </head>
      <body class="text-center">
        <main class="form-signin">
        <form>
           <!-- <img class="mb-4" src="./logo.png" alt="" height="300"> -->
            <h1 class="h3 mb-3 fw-normal"><b>My App</b> - Login</h1>
        
            <div class="form-floating">
              <input type="text" class="form-control" id="username" placeholder="test@example.com">
              <label for="floatingInput">Email address</label>
            </div>
            <div class="form-floating">
              <input type="password" class="form-control" id="password" placeholder="Password">
              <label for="floatingPassword">Password</label>
            </div>
        
            
            <button class="w-100 btn btn-lg btn-primary mt-3" type="submit">Login</button>
            
            <div id="myData"></div>
    
          </form>
        </main>
    
        <!--<script src="login.js"></script>    -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
        <script>
     
    
            document.querySelector("form").addEventListener("submit", e => {
            e.preventDefault(); /* and the rest */ 
               console.log("Inside click Login");
               const response = await fetch ('https://example.com/authenticate', 
          {
             method: 'POST',
             headers: {
              'Content-Type': 'application/json',
               'Username': 'demo@exk.com',
               'Password': 'Ch4ng3it!'
            },
        })
            console.log("Reached before ok");
              if (!response.ok) {
              throw new Error(`Error! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            console.log(result);
            
            
          
          document.getElementById(myData).innerHTML = result;
            
                
            })

 document.getElementById(myData).innerHTML = result;
    
        
    })
    /*async function clickLogin() {
        console.log("Inside click Login");
  //e.preventDefault();
  const response = await fetch ('https://example.com/authenticate', 
  {
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
       'Username': 'demo@exk.com',
       'Password': 'Ch4ng3it!'
    },
})
  /*.then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log('Request Failed', err))*/
  
    console.log("Reached before ok");
  
  /* if (!response.ok) {
      throw new Error(`Error! status: ${response.status}`);
    }
    
    const result = await response.json();
    
    console.log(result);
    
    
  
  document.getElementById(myData).innerHTML = "abcd";
}*/


    </script>
  </body>
</html>

Below is network trace.

enter image description here

Karan Nayyar
  • 666
  • 2
  • 7
  • 14
  • You aren't preventing your form from submitting normally – Phil Mar 23 '22 at 06:00
  • So what should I change ? – Karan Nayyar Mar 23 '22 at 06:01
  • what error u get in the console? – buga Mar 23 '22 at 06:05
  • No errors were logged in console. – Karan Nayyar Mar 23 '22 at 06:17
  • @Phil should I do like this
    and uncomment the //e.preventDefault(); LOC.
    – Karan Nayyar Mar 23 '22 at 06:18
  • I don't recommend using inline `on*` event attributes. I would use `document.querySelector("form").addEventListener("submit", e => { e.preventDefault(); /* and the rest */ })`. In any case, see the link at the top of your question for all sorts of options – Phil Mar 23 '22 at 06:20
  • 1
    @Phil even when triggered by the Enter key, or any other non-programmatic means, the click event will fire ion the linked – Kaiido Mar 23 '22 at 06:23
  • @Kaiido ah nice, I wasn't aware of that. I still prefer _submit_ event handling though – Phil Mar 23 '22 at 06:28
  • @Phil I tried . But still on network trace I see the fetch request status as unknown. Also, the I am not getting any response on the console log. – Karan Nayyar Mar 23 '22 at 06:31
  • Are there any other `
    ` tags in your document? Ideally you'd give your form an ID and use `document.getElementById()` instead of `querySelector("form")` which just grabs the first `
    ` in the document. I only used that because your original code only has one form
    – Phil Mar 23 '22 at 06:43
  • There should be errors in your console about using `await` outside an `async` function. You would need `.addEventListener("submit", async (e) => { e.preventDefault(); ... })` – Phil Mar 23 '22 at 06:46
  • @Phil didn't find any errors in console. I have enabled preserve logs on chrome dev tools. Let me try with the suggested changes – Karan Nayyar Mar 23 '22 at 06:48
  • In that case, clear your browser cache since there's no way it's running the code in your question without errors – Phil Mar 23 '22 at 06:51
  • Yeah I got an error saying uncaught syntaxerror await is only valid in async function. Made the change in code like async(e) => { ... } – Karan Nayyar Mar 23 '22 at 06:56
  • 1
    @Phil this resolved my issue. After clearing browser cache, I am no longer getting any errors and the fetch call is also passing with 200 ok status. – Karan Nayyar Mar 23 '22 at 07:09

0 Answers0