Request API with Javascript

Asked

Viewed 3,418 times

0

I am making a web application in which the goal will be to use an API to only list some information (GET) and for this I would like to use only Java and html.

The API is this: https://www.football-data.org/documentation/ and has key(headers).

const app = document.getElementById('root');

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);


var request = new XMLHttpRequest();
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function() {

  // Begin accessing JSON data here
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(movie => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

      const h1 = document.createElement('h1');
      h1.textContent = movie.title;

      const p = document.createElement('p');
      movie.description = movie.description.substring(0, 40);
      p.textContent = `${movie.description}...`;

      container.appendChild(card);
      card.appendChild(h1);
      card.appendChild(p);
    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
  }
}

request.send();
html {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-family: 'Dosis', sans-serif;
    line-height: 1.6;
    color: #666;
    background: #F6F6F6;
}

#root {
    max-width: 1000px;
    margin: 0 auto;
}

h1 {
    text-align: center;
    background-image: linear-gradient(120deg, #96af9f 0%, #9fc5a7 100%);
    margin: 0;
    font-size: 20px;
    color: white;
}

img {
    display: block;
    margin: 1rem auto;
    max-width: 8%;
}

p {
    text-align: center;
    margin: 0;
}

.container {
    display: flex;
    flex-wrap: wrap;
}

.card {
    background: white;
    box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
    overflow: hidden;
    transition: all .2s linear;
}

.card:hover {
    box-shadow: 2px 8px 45px rgba(0, 0, 0, .15);
    transform: translate3D(0, -2px, 0);
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    border: 1px solid #e7e7e7;
    background-color: #f3f3f3;
    margin-bottom: 30px;
}

li {
    float: left;
}

li a {
    display: block;
    color: #666;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #ddd;
}

li a.active {
    color: white;
    background-color: #9fc5a7;
}

@media screen and (min-width: 200px) {
    .card {
        flex: 1 1 calc(100% - 2rem);
    }
}

@media screen and (min-width: 900px) {
    .card {
        flex: 1 1 calc(100% - 2rem);
    }
}
<!DOCTYPE html>
<html lang="en">

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

  <title>Football stats</title>
  
  <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

</head>

<body>

  <div id="root">
    <img src="./img/logo.png" alt="logo">
    <ul>
      <li><a href="#home">Home</a></li>
      <li><a class="active"href="index.html">Today Matches</a></li>
      <li><a href="#contact">Portuguese League</a></li>
    </ul>  
  </div>

  <script src="app.js"></script>
</body>
</html>

The main idea is to make a list of the games of the day with the name of the championship and the respective game.

In the documentation you have this example of request in javascript/jquery:

$.ajax({

headers: { 'X-Auth-Token': 'YOUR_API_TOKEN' },

url: 'http://api.football-data.org/v2/matches?status='LIVE',

dataType: 'json',

type: 'GET',

}).done(Function(Sponse) {

// do Something with the Response, e.g. Isolate the id of a Linked Resource

console.log(Sponse);

});

The question is how I can make a connection to an api with headers?

  • That one headers who comments are the header of the request?

  • Have you tried the method setRequestHeader?

1 answer

3

Substitute

var request = new XMLHttpRequest();
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true);
request.onload = function() {

For

fetch('url da api', { headers:{ //seus headers } })
.then(retorno =>{ 
 //faz sua tratativa do retorno aqui.
 })
.catch(error => console.log(error))

Where the console log is you can do its function with everything else.

Enjoy a read on the fetch documentation

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Browser other questions tagged

You are not signed in. Login or sign up in order to post.