ABpositive
ABpositive

Reputation: 303

Fetch GET request unhandled rejection

I'm doing a basic request to a backend in JS (only to check a user instance exists and will return a bool (true/false) to prevent returning full user data until needed)

From what I have been told by peers it's ill-advised to be passing sensitive data (in this case people's emails) via paths and should be via the body (I haven't looked into why) Anyway, so the way I configured it was to be contained within the body like this:

GET http://localhost:8080/User/check
Content-Type: application/json
{
  "email" : "[email protected]"
}

However when doing this call in JS:

  if (isAuthenticated){
    console.log("test -----------")
    console.log(user.email)
    fetch("http://###.###.###.###:8080/User/check", {
       method: "GET", 
       headers:{"Content-Type":"application/json"},
       body: JSON.stringify( {
          email: "[email protected]"
       })
       
  }).then((result)=> {
    if (result.ok){
      console.log("sucess")
    }
    else{
      console.log("fail")
  }})}

I get this error:

Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

Is there a way to bypass this or am I restricted to using either a POST method and reworking my backend method or containing the users email inside of the path?

Upvotes: 0

Views: 333

Answers (1)

Batuhan Isildak
Batuhan Isildak

Reputation: 63

Firstly if you want to use body, you should use POST method. This is why the Fetch API keeps sending errors to you.

The second question is, why do we not use GET method while we are sending sensitive datas like emails, passwords etc. The answer is, entire URL is cached user's browser history and it may expose user's sensitive data. And it will be much more secure if you use POST method because it prevents data leakage via the query string (you are sending data in the body).

Upvotes: 1

Related Questions