skip to Main Content

i’ve given the api endpoint with GET method but i think it needs a body, when i test it on postman it works fine but in react native when i try to fetch it it shows error [TypeError: Body not allowed for GET or HEAD requests]

my backend partner send this curl, how to use the –data since GET are not recieving any body

    curl --request GET 
  --url http://base_url/api/v2/order/all 
  --header 'Content-Type: application/json' 
  --cookie 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjA4ODc3NzA5MjIxIiwidXNlcm5hbWUiOiJGbG8iLCJpYXQiOjE2NTEwMzIxNTYsImV4cCI6MTY1MTA3NTM1Nn0.JkwTPvjig7bd8Q27MvZ7DsUCz68Qyzh3EctFTRh-m0E; connect.sid=s%253AgtaL-l_60sBGAdEhTiHspbzX3rBBiEFg.O5z0JBi7Oqo1UXSZOxQckm2FNhG3A%252BWZod951CC5Cys' 
  --data '{
    "userId":"79025884",
    "limit":10,
    "page":1
}'

enter image description here

this is my function

function GetActivity() {
    const url = APIConfig.SERVER.ORDER + "/all";
    fetch(url, {
      method: "GET",
      headers: { "content-type": "application/JSON" },
      body: JSON.stringify({
            userId: "79025884",
            limit: 10,
            page: 1,
           }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("GetActivity Order:", data);
        setOrderList(data.data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }

3

Answers


  1. The same problem I faced several days ago, and I made some research about it. I can say that even though it is possible to use get method with body in postman you can’t use get method with body with fetch or axios, because body is not allowed. And I think you should allow post method in your backend if your want to send data. You can read in depth about it here.

    Login or Signup to reply.
  2. For a GET request, any parameters you want to pass to the API end point will need to be sent as part of the url I believe.

    E.g. http://example.com/id/1 (where 1 is the dynamic value for the ID parameter)

    I think the error you are seeing is because your trying to set a "body" value for a get request, which would be used with a POST request instead for example.

    Login or Signup to reply.
  3. You need to add it to the URI or the HTTP request headers depending on the data. Usually URI path for hierarchical resource identification data and URI query for non-hierarchical. There are standard HTTP headers for many things including pagination. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests They are for byte ranges, but you can use custom units like pages. Another way is doing pagination with URI.

    GET https://example.com/api/v1/orders/by-user-id/79025884/?page=1&limit=10
    GET https://example.com/api/v1/orders/by-user-id/79025884/ "Range: items=1-10"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search