Home > OS >  how to request API GET with Authentication (login)
how to request API GET with Authentication (login)

Time:01-21

I have this html script code:

<html>
    <head>
        <title>Curriculum</title>
        <link rel="stylesheet" href="style.css">
        <script type="text/javascript">
function myFunction() {

   url: 'https://www.fulek.com/data/api/supit/curriculum-list/hr',
   type: 'GET',
   contentType: 'application/json'
   headers: {
      'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254'
   },
   success: function (result) {
       console.log(result);
   },
   error: function (error) {

   }
}
    </script>
    </head>
    <body>
     <td><button type="button" onclick="myFunction()">Delete</button></td>
    </body>
</html>

and for some reason the fetch call doesn't work. I got the token when I logged in and got the data from the API: enter image description here Here is the error I got for some reason: enter image description here I have tried a few things but I can't really get it right as I almost dont have experience in JS.

CodePudding user response:

First, I'd recommend learning how promises & async/await work in Javascript before working with APIs.

The problem with your code is two-fold:

  1. You aren't returning anything from the function.
  2. You structured the response as an object. However, the object wasn't placed within curly braces { }.

I fixed the function in the snippet below. Hope this helps:

<html>
  <head>
    <title>Curriculum</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <button type="button" onclick="getData()">Delete</button>

    <script src="./testing.js"></script>

    <script>
      async function getData() {
        const response = await fetch("https://www.fulek.com/data/api/supit/curriculum-list/hr", {
          method: "GET",
          headers: {
            "Content-Type": "text/plain;charset=UTF-8",
            Authorization:
              "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvb0JHIiwibmJmIjoxNjc0MjMxMjUwLCJleHAiOjE2NzQyMzQ4NTAsImlhdCI6MTY3NDIzMTI1MH0.2HOTHD3kmxFg1PH0UTD7yv7dGv-kM1j2OJsdfgCZ254",
          },
        });
        const data = response.json()

        return data.then(response => console.log(response.data));
      }
    </script>
  </body>
</html>

  • Related