Aditya Rohilla
Aditya Rohilla

Reputation: 337

How can I send data through fetch API by GET request?

I want to send some data via fetch API to a server so that it can query a DB based on that. Unlike Ajax i can't find any suitable method to do so. Here is my fetch call:

{fetch("http://192.168.90.53:4000/game/[email protected]", {method: "GET"} )
        .then((response) => response.json())
        .then((responseData) => {
            id= responseData.id;
            name= responseData.name; 
            console.log(responseData);
        })
       .catch((error) => {
             console.warn(error);
           }); 
  }
}

I want to send a parameter such as email, so that the server can query the DB using that. I am using react-native android hence can't use an Ajax request. I want to use GET method only. Currently, the query params I'm passing in the URL aren't shown by the server in req.query

Upvotes: 10

Views: 23164

Answers (3)

Ryan Dines
Ryan Dines

Reputation: 1037

Try escaping the @ character with %40 or doing something like {fetch("http://192.168.90.53:4000/game/?email=" + encodeURIComponent('[email protected]'), {method: "GET"} )...

Upvotes: 2

John Shammas
John Shammas

Reputation: 2715

GET requests do not support bodies, and parameters must be sent in the URL as you have shown in your example. If you're not able to see them on the server-side, it may be an issue with the server which should be asked as a separate question.

As a sanity test, navigate to that URL in a browser (or a tool like Postman) and test that the result is correct, before implementing the call with fetch, so that you'll at least confirm if it's a server issue or a JavaScript issue.

Upvotes: 10

Liem Ly Quan
Liem Ly Quan

Reputation: 71

You can add that like below

fetch("http://192.168.90.53:4000/game", obj)  
.then(function(response) => response.json())
.then((responseData) => {
  id = responseData.id;
  name = responseData.name; 
  console.log(responseData);
},
.catch((error) => {
  console.warn(error);
}); 

var obj = {  
  method: 'POST',
  body: JSON.stringify({
    'email': your_email_here,
  })
};

Upvotes: -3

Related Questions