2

I started recently working with the fetch library in javascript to execute a few POST/GET calls I need, and am having trouble getting the response data in successful calls.

This is my current code, where I am trying to request an authentication token:

var request = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json"
  },
  body: JSON.stringify({
    username: username,
    password: password,
  })
} 
fetch('http://127.0.0.1:8000/api/login/', request)
.then(function(response) {
  if (response.ok) {
    console.log("SUCCESS");
  } else {
    console.log("FAIL");
  }
});

Interesting enough, when I send empty strings, which results in a response with error code 400, I get an expected FAIL in the console. The problem happens when I successfully send correct authentication details. In that case, SUCCESS should be printed, but instead nothing is printed out in the console. In the server itself, I am seeing an expected POST request with a 200 response, indicating that authentication was OK.

What am I doing wrong here?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
jhc
  • 1,739
  • 3
  • 21
  • 46
  • Possible duplicate of [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – sideshowbarker May 28 '19 at 00:25
  • If the server isn’t sending an `Access-Control-Allow-Origin` response header in its response—or if it is but the value of that header doesn’t match the origin at which your frontend JavaScript code is running—then your browser’s blocking your frontend code from accessing the response. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details. If that’s what’s happening, then your browser should also be logging an error message in the browser devtools console to let you know that’s what’s going on. – sideshowbarker May 28 '19 at 00:26

0 Answers0