G
G
gomerIT2021-01-28 19:48:20
JavaScript
gomerIT, 2021-01-28 19:48:20

How can I track fetch whether json response came or not?

const request = await fetch(url, {
     method: 'POST'
  });

if (request.ok) {
  const response = await request.json();
} else {
   console.log('Ошибка сервера');
 }

As after the request.ok condition, I can check if I received a json response, because if the layout comes, then the application will simply fly away from me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-01-28
@gomerIT

probably request.json()throw up with an error if not JSON was returned there.
Therefore, it is enough to wrap in try..catch:

let response;
try {
  response = await request.json();
} catch (err) {
  console.error(err);
  return;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question