0

It is a very simple fetch api but for some reason I dont know why the body is not working. here is the code.

<label id="msg"></label>
<label id="msg2"></label>
<script type="text/javascript">

    const myRequest = new Request('some url', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({"email" : "email",
                                              "password" : "password"}),
                        mode: 'no-cors'});
    const myMethod = myRequest.method; // POST
    const bodyUsed = myRequest.bodyUsed; // true

    fetch(myRequest)
      .then(response => {
        if (response.status === 200) {
          return response.json();
        } else {
          //throw new Error('Something went wrong on api server!');
        }
      })
      .then(response => {
        document.getElementById("msg").innerHTML = response;
        document.getElementById("msg2").innerHTML = bodyUsed+" "+myMethod;
      }).catch(error => {
        document.getElementById("msg").innerHTML = error;
      });
</script>  

Is there anything I am doing wrong? I have stringify the body, changed the header but still when it runs, it shows false in msg2 label (which is nothing but just the body part of the request, just to be sure). which means the body is actually NaN. where is the problem and whats the solution?

Wahid Masud
  • 993
  • 10
  • 35

1 Answers1

2
mode: 'no-cors'

This means I do not want to do anything that would require the server to use CORS to grant permissions; do not throw CORS related errors.

Reading the response across origins requires the server grants permissions with CORS.

You said you weren't going to do that, so fetch does not try to make the body available to you.

(You are also prevented from doing anything that would require a preflight request, such as setting the Content-Type request header to JSON.)

Don't set the mode to no-cors.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • if I dont set no-cors then it shows error `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled` – Wahid Masud Jan 24 '18 at 16:11
  • @WahidMasud — As I said: "Reading the response across origins requires the server grants permissions with CORS." See https://stackoverflow.com/a/35553666/19068 – Quentin Jan 24 '18 at 16:12
  • alright i get it. i need to enable cors to get the body by fetch. i enabled it and it throws an exception `TypeError: Failed to fetch` why? – Wahid Masud Jan 24 '18 at 16:23