How to make a GET request in Javascript?

Asked

Viewed 190 times

0

I am a beginner in programming and am doing some projects and studying to build a portfolio. My current problem is with an image API (Unsplash). I first tested by Somnia I made a GET request to https://api.unsplash.com/photos/random, there I provided the API Client-ID in the Authorization header and successfully received a JSON with the image link and other information. My bottleneck is time to codify this. I tried to use fetch as in the code below:

    function setWallpaper() {
        fetch(`https://api.unsplash.com/photos/random`).then(response => {
            return response.json();
        })
        .then(data => {
            const { id } = data.id
            console.log(id);
        })
    }

I hope to receive the image ID, but on the console nothing appears. Maybe it’s because we still have to put the Client-ID in the Authorization header, but I don’t know where to put this information in the code.

  • In const { id } = data.id actually you create an object and throw it away. Try const id = data.id and your code should work.

1 answer

0

Exactly as explained on MDN:

Example:

const myHeaders = new Headers({
    'Header-do-Client-ID': 'valor do header do Client-ID'
});

const myInit = {
  method: 'GET',
  headers: myHeaders
};

const myRequest = new Request('https://api.unsplash.com/photos/random', myInit);

fetch(myRequest).then(response => {
    return response.json();
})
.then(data => {
    const { id } = data.id
    console.log(id);
});

Obviously change Header-do-Client-ID by the name of the correct header and exchange the valor do header do Client-ID also. An example if it were with bearer (possibly):

const token = 'valor aqui';

const myHeaders = new Headers({
    'Authorization': `Bearer ${token}`
});

const myInit = {
  method: 'GET',
  headers: myHeaders
};
  • How do I know if the values have been returned correctly? The console.log(id) is not displayed in the browser, I think is not getting the json...

  • @Davidlima look at the console, see if any error occurred.

  • @Davidlima is entering the then or not?

Browser other questions tagged

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