1

I need to be able to fetch invoice data from this api: https://apidoc.qoyod.com/

and display it on my page through javascript. First, the user enters an api key and then the page displays the invoice index and details.

This is the code I have so far:

function displayData()
{

 const div = document.getElementById("result");


 const URL = 'https://www.qoyod.com/api/2.0/invoices/1';

   
   fetch(URL)
   
   .then((resp) => resp.json())
  
   .then(function(data)
   {
    let invoices = data.results;
    invoices.map(function(invoice){
     let p = document.createElement('p');
     p.innerHTML=`${invoice.index}`;
     
     div.appendChild(p);     
    })   
   })
 
  
  
  .catch(function(error) {
    console.log(json.stringify(error));
  })
  }
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Qoyod Assignment</title>

  <link href="styles.css" rel="stylesheet">

<script type="text/javascript" src="scripts.js"></script>

<script type="text/javascript">

</script>

</head>

<body>

  <div id="root">
  
<input style="float: left; margin-right: 10px;" type="text" placeholder="Enter API Key" />
<button onClick="displayData();" >Display Data</button>
<div id="result"></div>

</body>


</html>

The challenge here is the "fetch" part. I am sure there is something I am missing out on while extracting the data. Maybe I'm not using the API URL correctly? I just can't seem to be able to "grab" the API data into my"data" object. When I click the button, I get no output at all!

Also, I need to figure out how to use the entered api key to fetch the data. I honestly have no clue at all. It's my first time to work with apis and I feel sooo lost :((

If there are any API pros out there, I would greatly appreciate your assistance!

Thanks

UPDATE: I managed to add the api as a header while fetching the data in this format:

fetch(URL, {
  headers: new Headers({
    'API-KEY' : '[api-key-here]' })
})

However, I got this error in my browser: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.qoyod.com/api/2.0/invoices/1. (Reason: CORS request did not succeed)."

Does this mean I need to be granted access by the owner of the api server?

maha
  • 277
  • 1
  • 5
  • 15
  • `json.stringify` Capitalization often matters in programming. – CertainPerformance Oct 12 '18 at 04:47
  • Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – Ridcully Oct 13 '18 at 05:37
  • It is usually a bad idea to put your API-KEY in the frontend of your website. You should have a backend where you request from the API in the backend and then render the data in your frontend. You are facing Cross-Origin issues because you are requesting from a different URL than the one you already used to load the frontend. This is a security measure in many APIs endpoints. – busaud Mar 05 '23 at 18:21

2 Answers2

0

Try to run below code snippet. and make sure you have data in correct JSON Object format. Below i try to replicate the problem. assume you have data in data variable after Ajax call.

function displayData() {
  const div = document.getElementById("result");

  /* const URL = 'https://www.qoyod.com/api/2.0/invoices/1';

     fetch(URL)
     
     .then((resp) => resp.json())
    
     .then(function(data)
     { */

  let data = {
    results: [{
        "index": 1,
        "code": "170"
      },
      {
        "index": 2,
        "code": "175"
      }
    ]
  };

  let invoices = data.results;
  invoices.map(function(invoice) {
    let p = document.createElement('p');
    p.innerHTML = `${invoice.index}`;

    div.appendChild(p);
  })
  // })
  /*
  .catch(function(error) {
    console.log(json.stringify(error));
  })*/
}    
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Qoyod Assignment</title>

  <link href="styles.css" rel="stylesheet">

  <script type="text/javascript" src="scripts.js"></script>

</head>

<body>

  <div id="root">

    <input style="float: left; margin-right: 10px;" type="text" placeholder="Enter API Key" />
    <button onClick="displayData();">Display Data</button>
    <div id="result"></div>

</body>

</html>   

 
Shiv Kumar Baghel
  • 2,464
  • 6
  • 18
  • 34
  • Thanks for the quick response! the code you gave me produced the following output: 1 2 – maha Oct 12 '18 at 05:09
  • But, how do i get it to fetch the actual data from the api? – maha Oct 12 '18 at 05:13
  • i thought you are getting data from API successfully and have issue in render into `result` div. – Shiv Kumar Baghel Oct 12 '18 at 05:15
  • Oh no my challenge is to EXTRACT the data from the API after the user entering the API key – maha Oct 12 '18 at 05:48
  • what the error you are getting for fetching data exactly ? – Shiv Kumar Baghel Oct 12 '18 at 06:32
  • I am just not getting any data on the screen. When I click the button, nothing happens. – maha Oct 12 '18 at 08:04
  • I really hope you can help me write the correct code that will extract the data I need from the api: https://apidoc.qoyod.com... Thanks – maha Oct 12 '18 at 17:38
  • whats the issue in `fetch` for api? have you tried in `postman` ? – Shiv Kumar Baghel Oct 16 '18 at 02:03
  • No I don't know how to use postman, and I currently have limited time to finish this assignment, so can't learn a new program.. I am just using plain JavaScript to do this. – maha Oct 16 '18 at 03:50
  • its a simple software and plugin to test your api. just add into your chrome browser to test `postman` https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en – Shiv Kumar Baghel Oct 16 '18 at 04:06
  • Anyhow, the last error I was getting on chrome was this: "OPTIONS https://www.qoyod.com/api/2.0/invoices/1 404 displayData @ scripts.js:9 onclick @ (index):21 (index):1 Failed to load https://www.qoyod.com/api/2.0/invoices/1: Response for preflight does not have HTTP ok status. (index):1 Uncaught (in promise) TypeError: Failed to fetch", and when I shared it with the api owner they said: "our servers do not reply to OPTIONS requests and that is unchangeable". Is there anything I can do to make it work? – maha Oct 16 '18 at 04:19
  • and btw I just downloaded the postman plugin on chrome, and retested the api connection on chrome but it still failed.. Is there some kind of configuration I need to do to make my application work with postman? – maha Oct 16 '18 at 04:20
-1

If you are use postman than its very easy to you. You need api key pass to header and they already provide what data pass in body. enter image description here

enter image description here

Silence Peace
  • 341
  • 4
  • 13
  • Thanks for your reply. Can I use the "fetch" statement instead of xmlhttprequest? – maha Oct 13 '18 at 05:27
  • @maha yes you can use. – Silence Peace Oct 13 '18 at 07:11
  • I was able to attach the header to the fetch request. But, now I am getting this error: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.qoyod.com/api/2.0/invoices/1. (Reason: CORS request did not succeed).".. How can i solve this issue? (FYI I am not using postman) – maha Oct 13 '18 at 11:27