Make a GET request with fetch

2

Hello recently I am learning to use fetch I found on the internet an api which offers me a random user service now I have been trying to make a simple request where I only return a JSON that contains female users, and from a specific country like for example "US" according to the documentation of the same api I can do the following link but when I was investigating about fetch I found that I can make requests by passing what I want to obtain through a request for example

var miInit = { method: 'GET',
               headers: misCabeceras,
               mode: 'cors',
               cache: 'default' };

pass myInit as second parameter in fetch. Now when I try to do the same thing but with the api, it does not turn out that it returns me users of male gender and of other nationalities could they explain to me what I am doing wrong? below I leave my code

async function request(){

    let dataRequest = {
       method: 'GET', 
       headers: {gender: "female", nat:"US"}
    }
    let response = await fetch("https://randomuser.me/api", dataRequest);
      console.log(response)
    let result = await response.json();
      console.log(result)
}

request()
    
asked by Carlos Puente 06.10.2018 в 04:41
source

2 answers

3

The headers and the parameters are totally different things, maybe this is closer to what you are looking for and what is recommended by the standard fetch

async function request(){
    let url = new URL("https://randomuser.me/api");
    const params = {gender: "female", nat:"US"};
    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
    const dataRequest = {
       method: 'GET'
    };
    let response = await fetch(url, dataRequest);
      console.log(response)
    let result = await response.json();
      console.log(result)
}

More information      link

    
answered by 06.10.2018 / 06:37
source
2

It does not return the result you expect because you are passing the parameters as headers.

Try replacing:

let response = await fetch("https://randomuser.me/api", dataRequest);

By:

let response = await fetch("https://randomuser.me/api/?gender=female&nat=gb", dataRequest);
    
answered by 06.10.2018 в 04:49