简体   繁体   中英

how to request API GET with Authentication (login)

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: 在此处输入图像描述 Here is the error I got for some reason: 在此处输入图像描述 I have tried a few things but I can't really get it right as I almost dont have experience in JS.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM