Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 839
Aditya Rohilla Avatar asked Dec 31 '15 08:12

Aditya Rohilla


People also ask

How do you get data from an API using Fetch?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I send a POST request using fetch API?

POST request using fetch API: To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.


2 Answers

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.

like image 163
John Shammas Avatar answered Sep 22 '22 10:09

John Shammas


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

like image 24
Ryan Dines Avatar answered Sep 25 '22 10:09

Ryan Dines