Fetch ошибка 500

We have the following call to fetch.

this.http.fetch('flasher', { method: 'post', body: jsonPayload })
    .then(response => response.json())
    .then(data => console.log(data));

This works when we receive a 200 response but logs nothing to the console when we receive a 500 response. How do we handle a 500?

AndreaBogazzi's user avatar

asked Mar 25, 2016 at 18:35

Shaun Luttin's user avatar

Shaun LuttinShaun Luttin

134k82 gold badges405 silver badges467 bronze badges

2

Working Solution

Combining then with catch works.

fetch('http://some-site.com/api/some.json')  
  .then(function(response) {                      // first then()
      if(response.ok)
      {
        return response.text();         
      }

      throw new Error('Something went wrong.');
  })  
  .then(function(text) {                          // second then()
    console.log('Request successful', text);  
  })  
  .catch(function(error) {                        // catch
    console.log('Request failed', error);
  });

Details

fetch() returns a Promise containing a Response object. The Promise can become either fulfilled or rejected. Fulfillment runs the first then(), returns its promise, and runs the second then(). Rejection throws on the first then() and jumps to the catch().

References

MDN — Promise

MDN — Checking that the fetch was successful

Google — Introduction to Fetch

answered Mar 25, 2016 at 19:02

Shaun Luttin's user avatar

Shaun LuttinShaun Luttin

134k82 gold badges405 silver badges467 bronze badges

2

Just try to wrap in an object like console.log({data})

Fedor's user avatar

Fedor

17.2k14 gold badges40 silver badges131 bronze badges

answered Jan 13 at 7:22

allweek's user avatar

Старый

29.05.2020, 14:11

Новичок на форуме

Отправить личное сообщение для BJester

Посмотреть профиль

Найти все сообщения от BJester

 

Регистрация: 29.05.2020

Сообщений: 2

ошибка 500 fetch

Здравствуйте, возникла проблема. Я написал форму регистрации, которая успешно работает, после чего написал js файл, который обращается к серверу через fetch GET методом и всё ок. Но когда я сделал форму логина и повторил всё уже с методом POST, то сервер выдаёт ошибку 500, причём сама форма логина работает, однако если подключить js файл с fetch то случается error. Есть идеи с чем это может быть связано?
форма логина

<!DOCTYPE HTML>
<html>
<head>
    	<title>Login</title>
</head>
<body>
    	<form method="POST" action="https://test-publicapi.maximarkets.org/Account/logon">
	<p>
		<label>Login<br>
			<input name="email" type="email" size="40" id="log">
		</label>
	</p>
	<p>
		<label>Password<br>
			<input name="password" type="password" size="40" id="pass">
		</label>
	</p>
	<p>
		<button type="submit">Вход</button>
	</p>
	</form>
	<script src="scriptforlog.js"></script>
</body>
</html>

Вот js файл

async function onFormSubmit(evt) {
evt.preventDefault();

let email = document.getElementById('log').value;
let password = document.getElementById('pass').value;
let skip2Fa = true;

let data = new FormData();
data.append('email',email);
data.append('password',password);
data.append('skip2Fa',skip2Fa);

const response = await fetch(`https://test-publicapi.maximarkets.org/Account/logon`, {
method: "POST", body: data
});
if(response.ok) {
alert('ok');
} else {
alert('wrong');
};
}

const form = document.querySelector('form');
form.addEventListener('submit' , onFormSubmit);

Ответить с цитированием

Старый

30.05.2020, 02:49

Аватар для Malleys

Профессор

Отправить личное сообщение для Malleys

Посмотреть профиль

Найти все сообщения от Malleys

 

Регистрация: 20.12.2009

Сообщений: 1,714

Есть идеи с чем это может быть связано?

Вы отправляете данные в разных форматах — когда отправляли напрямую через форму, то там был тип application/x-www-form-urlencoded, (такой же, как у текстового представления класса URLSearchParams), что очевидно принимается сервером.

А класс FormData в конечном счёте представляет данные при отправке в виде типа multipart/form-data, а вам нужен application/x-www-form-urlencoded. Можно перевести из одного формата в другой, а можно сразу правильный.

Например, замените (строка №8) FormData на URLSearchParams.

Ответить с цитированием

Старый

30.05.2020, 13:19

Новичок на форуме

Отправить личное сообщение для BJester

Посмотреть профиль

Найти все сообщения от BJester

 

Регистрация: 29.05.2020

Сообщений: 2

Спасибо, я уже понял что проблема была в формате данных, однако я решил проблему таким способом(добавил headers)

function onFormSubmit(evt) {
evt.preventDefault();

let mail = document.getElementById('log').value;
let pass = document.getElementById('pass').value;

fetch('https://test-publicapi.maximarkets.org/Account/logon', {  
	method: 'POST',
    	headers: {
    		'Accept': 'application/json',
    		'Content-Type': 'application/json'
    	},
    	body: JSON.stringify({
		email: mail,
		password: pass,
	})
});


}
const form = document.querySelector('form');
form.addEventListener('submit' , onFormSubmit);

Ответить с цитированием

Старый

30.05.2020, 17:09

Профессор

Отправить личное сообщение для laimas

Посмотреть профиль

Найти все сообщения от laimas

 

Регистрация: 14.01.2015

Сообщений: 12,990

Сообщение от Malleys

multipart/form-data, а вам нужен application/x-www-form-urlencoded

А чем смешанный тип не подойдет? Статус 500, это в первую очередь нужно смотреть логи на сервере и устранять причину на нем.

Ответить с цитированием

Старый

04.06.2020, 01:53

Аватар для Malleys

Профессор

Отправить личное сообщение для Malleys

Посмотреть профиль

Найти все сообщения от Malleys

 

Регистрация: 20.12.2009

Сообщений: 1,714

Сообщение от laimas

А чем смешанный тип не подойдет?

Пусть имеется адрес «dimityr.novakov@gmil.com» и пароль «anybody!has@got#to$learn%sometime», которые нужно передать на сервер. Давайте посмотрим, как можно представить эти данные для передачи…

  • multipart/form-data

    Код:

    ------WebKitFormBoundaryfJQTzzfNQvHhuVKC
    Content-Disposition: form-data; name="email"
    
    dimityr.novakov@gmil.com
    ------WebKitFormBoundaryfJQTzzfNQvHhuVKC
    Content-Disposition: form-data; name="password"
    
    anybody!has@got#to$learn%sometime
    ------WebKitFormBoundaryfJQTzzfNQvHhuVKC--
  • application/x-www-form-urlencoded

    Код:

    email=dimityr.novakov%40gmil.com&password=anybody%21has%40got%23to%24learn%25sometime
  • application/json

    Код:

    {"email":"dimityr.novakov@gmil.com","password":"anybody!has@got#to$learn%sometime"}

Т. к. передача файлов не нужна в данном случае, то наверно следует отдавать предпочтение менее многословному формату!

Сообщение от laimas

Статус 500, это в первую очередь нужно смотреть логи на сервере и устранять причину на нем.

Многие общественные API могут такое возвращать, однако это скорей означает, что следует посылать данные в правильном формате.

Ответить с цитированием

Старый

04.06.2020, 07:09

Профессор

Отправить личное сообщение для laimas

Посмотреть профиль

Найти все сообщения от laimas

 

Регистрация: 14.01.2015

Сообщений: 12,990

Сообщение от Malleys

однако это скорей означает, что следует посылать данные в правильном формате.

Ой ли так это на самом деле? И остальное ну чушь полнейшая, ибо на то он и смешанный тип, и он никак не может стать причиной ошибки отправки им вместо application/x-www-form-urlencoded.

Ответить с цитированием

Старый

04.06.2020, 09:24

Аватар для Malleys

Профессор

Отправить личное сообщение для Malleys

Посмотреть профиль

Найти все сообщения от Malleys

 

Регистрация: 20.12.2009

Сообщений: 1,714

Сообщение от Malleys

И остальное ну чушь полнейшая

Какие предъявы? Посчитай байты!

Сообщение от laimas

ибо на то он и смешанный тип, и он никак не может стать причиной ошибки

Конечно же можешь посылать данные во всех возможных форматах, однако разработчики серверного кода могли написать только обработку, например, для типа json, а на всё остальное завершение со статусом 404 или 500 или найди ещё «Я — чайник!» или ещё что!

Сообщение от laimas

на то он и смешанный тип, и он никак не может стать причиной ошибки

«Не хотим принимать такое — завершили как смогли!»

Ответить с цитированием

Старый

04.06.2020, 09:53

Профессор

Отправить личное сообщение для laimas

Посмотреть профиль

Найти все сообщения от laimas

 

Регистрация: 14.01.2015

Сообщений: 12,990

Слушай, гений ты наш, ты практически ответил на возможную причину ошибки тем, что вместо application/x-www-form-urlencoded отдается тип multipart/form-data, что является просто бредом. Все дальнейшие твои рассказы, это пересказ документации, которую я и без тебя знаю.

И хотя бы поинтересовался каковы причины могут порождать статус 500, и корректно ли будет бездумно при этом выплевывать его клиенту, пусть мается в догадках. А то гонишь пургу, баз какой-то беспредметный.

Ответить с цитированием

Старый

04.06.2020, 10:26

Аватар для Malleys

Профессор

Отправить личное сообщение для Malleys

Посмотреть профиль

Найти все сообщения от Malleys

 

Регистрация: 20.12.2009

Сообщений: 1,714

Сообщение от laimas

И хотя бы поинтересовался каковы причины могут порождать статус 500, и корректно ли будет бездумно при этом выплевывать его клиенту, пусть мается в догадках.

Вам уже отвечали — неверный формат данных запроса. А чём вам не подходит ответ в формате JSON?

Сообщение от laimas

ты практически ответил на возможную причину ошибки тем, что вместо application/x-www-form-urlencoded отдается тип multipart/form-data

Я писал про отправку на сервер в формате multipart/form-data (и автор темы тоже), а не про отправку клиенту, которая кстати, происходит в формате JSON. И отправка клиенту статуса 500, а также сопутствующих данных тоже происходит в формате JSON…

{
	"errorType": 1,
	"statusCode": 500,
	"message": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.",
	"messageDetail": null,
	"validationErrors": null,
	"padString": null
}

Сообщение от laimas

Все дальнейшие твои рассказы, это пересказ документации

Какой пересказ? Даже автор темы давно понял, что «проблема была в формате данных».

Ответить с цитированием

Старый

04.06.2020, 10:38

Профессор

Отправить личное сообщение для laimas

Посмотреть профиль

Найти все сообщения от laimas

 

Регистрация: 14.01.2015

Сообщений: 12,990

Сообщение от Malleys

Вам уже отвечали — неверный формат данных запроса. А чём вам не подходит ответ в формате JSON?

Значит так: если речь об API, то нормальный разработчик обязательно опишет параметры запроса, иначе, что вполне естественно, с API нельзя будет работать. В том что такое случилось скорее вина пользователя не удосужившегося прочесть документацию, и обнаружившего решение методом научного тыка.

Ты же начал совсем с иного, что вообще никоим образом не могло быть источником проблемы. Все остальное, это ради поболтать.

PS. Кстати, отвечать клиенту статусом 404 на ошибку несоответствия типу, это вообще из рук вон.



Последний раз редактировалось laimas, 04.06.2020 в 12:03.

Ответить с цитированием

When making HTTP requests with the Fetch API, it’s important to handle error responses properly. One common error response is the HTTP 500 status code, which indicates an internal server error. In this guide, we’ll walk through how to handle a 500 response with the Fetch API, including code examples.

Using try…catch

One way to handle errors with the Fetch API is to use the try…catch statement. This allows us to catch any errors that occur during the fetch request and handle them appropriately.

try {
  const response = await fetch('/api/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  // handle successful response here
} catch (error) {
  // handle error response here
  console.error('There was a problem with the fetch operation:', error);
}

In this example, we first make the fetch request to the `/api/data` endpoint. We then check if the response was successful by checking the `ok` property. If the `ok` property is false, we throw an error.

The `catch` block then handles any errors that occur during the fetch request. In this case, we simply log the error to the console.

Handling a 500 response

To specifically handle a 500 response, we can modify the `if (!response.ok)` check to look for the specific HTTP status code:

try {
  const response = await fetch('/api/data');
  if (response.status === 500) {
    throw new Error('Internal server error');
  }
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  // handle successful response here
} catch (error) {
  // handle error response here
  console.error('There was a problem with the fetch operation:', error);
}

In this example, we first check if the response status code is 500. If it is, we throw an error specific to the 500 response.

If the response status code is not 500, we continue with the `if (!response.ok)` check as before.

Conclusion

Handling error responses with the Fetch API is an important part of building reliable applications. By using the try…catch statement and checking for specific status codes, we can ensure that our applications handle error responses properly.

Follow us on Social Media

Fetch 500 Internal Server Error With Code Examples

Hello everyone, in this post we will examine how to solve the Fetch 500 Internal Server Error programming puzzle.

Error on app.js:5581 - Error about fetch
POST http://localhost:8080/login 500 (Internal Server Error)

To understand any type of internal server errors, you can check your network.
On web browser, click on inspect network and on the network error that appears, 
click on the login file and you see the error in the options of everything, 
fetch/xhr, js... 

Or in another cases, your redirect has an mistake.

We have shown how to address the Fetch 500 Internal Server Error problem by looking at a number of different cases.

How do I fix a 500 Internal server error?

Clear your browser cache and cookies Check these articles on deleting the cache on an Android phone or iPhone, if you use a mobile device. Alternatively, you can test opening the page from another browser. For instance, if you use Chrome, try Firefox or vice versa.

Why does 500 internal error mean?

The HTTP 500 internal server error is a general-purpose error code that means there is a problem on the website’s server, but the exact problem couldn’t be definitively identified. In other words, the server doesn’t know what the exact problem is.28-Mar-2022

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. This error response is a generic “catch-all” response.13-Aug-2021

How do I fix request failed with status code 500?

How to Fix the 500 Internal Server Error

  • Backing Up Your Site. These solutions require making a lot of changes in your site’s root directory .
  • Server permission.
  • Server timeout.
  • Script timeout.
  • Errors in .
  • Check the Error Logs.
  • Clear your browser cookies and cache.
  • Reload or Refresh the Webpage.

Why do I get an internal server error?

An “Internal Server Error” happens within the web server attempting to show you a web page. It’s usually a server-side problem out of your control. The server encountered an internal error or misconfiguration and was unable to complete your request.

How do I fix error 500 in Chrome?

How to fix: HTTP Error 500 in Google Chrome

  • Reloading/Refreshing the web page on which you encountered the issue.
  • Clearing the cookies of your browser.
  • Deleting your browser’s cache.

How do I fix 500 internal server error IIS?

IIS error The error 500.19 is an internal server error often occurring on a server using Microsoft IIS software. It indicates that the configuration data for the page is invalid. To solve the issue, delete the malformed XML element from the Web. config file or from the ApplicationHost.

How do I fix server problems?

Let’s take a look at ten potential ways you can fix “DNS Server Not Responding” on Windows and Mac devices.

  • Switch to a Different Browser.
  • Start Your Computer in Safe Mode.
  • Temporarily Disable Your Antivirus Software and Firewall.
  • Disable Secondary Connections.
  • Disable the Windows Peer-to-Peer Feature.
  • Restart Your Router.

What is 500 Internal Server error stack overflow?

a “500 hundred internal server error” is the HTTP status code returned by a web server when the URL you requested causes the server to encounter an error attempting to serve a response. A “stack overflow” is the particular error that is being encountered.

How do I get a 500 internal server error postman?

Unblock yourself

  • Make sure there is no error in the configuration of your request. Look for typos, whitespaces, or invalid JSON formatting.
  • Compare the API documentation of the service you’re making a call to with the configuration of your request. Check that the elements below are configured correctly in the request:

Follow us on Social Media

Quiz: What does this call to the web’s new fetch() API do?

fetch("http://httpstat.us/500")
    .then(function() {
        console.log("ok");
    }).catch(function() {
        console.log("error");
    });

If you’re like me, you might assume this code logs “error” when run—but it actually logs “ok”.

This expectation probably comes from years of jQuery development, as jQuery’s ajax() method invokes its fail handler when the response contains a failed HTTP status code. For example, the code below logs “error” when run:

$.ajax("http://httpstat.us/500")
    .done(function() {
        console.log("ok");
    }).fail(function() {
        console.log("error");
    });

Why does fetch() work this way?

Per MDN, the fetch() API only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” Basically fetch() will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.

The good is news is fetch provides a simple ok flag that indicates whether an HTTP response’s status code is in the successful range or not. For instance the following code logs “Error: Internal Server Error(…)”:

fetch("http://httpstat.us/500")
    .then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

To keep this code DRY and reusable, you probably want to create a generic error handling function you can use for all of your fetch() calls. The following code refactors the error handling into a handleErrors() function:

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(function(response) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

For added fun you can use ES6 arrow functions to make the callback formatting a little less verbose:

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}
fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok") )
    .catch(error => console.log(error) );

Parting thoughts

Although I still don’t like fetch()’s lack of rejecting failed HTTP status codes, over time fetch()’s behavior has grown on me—mostly because it gives me more control over how I handle individual problems. Plus, the composable nature of fetch() makes it fairly trivial to manually handle errors without adding a bunch of verbose code.

Overall I think it’s worth taking few minutes to play with fetch(), even if it’s just to see what you think. It’s certainly a far more readable alternative to XMLHttpRequest. If you happen to be building NativeScript apps, you might not know that you can use fetch() today without any need for a polyfill or fallback. And something about using fetch() to perform HTTP requests in native Android and iOS apps is just plain cool :)

This article was updated on September 15th, 2015 to use a simpler handleErrors() function based on a comment from Jake Archibald.

Понравилась статья? Поделить с друзьями:
  • Fetch ошибка 403
  • Fetch ошибка 401
  • Ferrum ошибка e01
  • Fetch first git ошибка
  • Fetch completed 1с код ошибки 4