0

Here is the code:

await fetch("http://localhost:3000/login", {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    login: name,
    password: pass
  }),
})
.then(async() => {
  await AsyncStorage.setItem('Login', name)
})
.catch(err => alert(err));

When I try to intentionally make a mistake in order to test the logging process, I get the error in the "Network" tab of my browser, but my website thinks that everything is fine and it executes the .then() code, even though it obviously shouldn't do that, because the Promise is rejected (it says POST http://localhost:3000/login 400 (Bad Request) in the console).

I tried a different code

.then(async () => {
    await AsyncStorage.setItem('Login', name) 
  }, (reason) => 
  alert(reason)
);

But it too doesn't work the way I want, it should execute this part (reason) => alert(reason)).

What's the solution?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • `fetch` doesn't reject its promise on HTTP errors, only network-level errors. (I think it's a bit of an API footgun, to be blunt.) You need to check `ok` on the response object you receive as the fulfillment value of the initial promise. I wrote it up [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder Sep 01 '21 at 16:13
  • 2
    Side note: Combining `async`/`await` with `.then`/`.catch` tends to get pretty confusing, best to use one or the other, not both. Example of fixing both: https://pastebin.com/pgAfj38D – T.J. Crowder Sep 01 '21 at 16:14

0 Answers0