Rest error 400

Что такое ошибка сервера 400 Bad Request и как ее можно самостоятельно исправить. Пошаговые инструкции и советы. Исправление Bad Request на стороне клиента и сервера.

Раздражает, когда какой-то сайт не загружается и отзывается непонятными ошибками. Обычно они сопровождаются одним из десятков HTTP-кодов, которые как раз намекают на характер сбоя, а также его вероятные причины. 

В этом материале поговорим об ошибке 400 Bad Request. Почему она появляется и как ее исправить. 

Чуть подробнее об ошибке 400

Как и другие коды, начинающиеся на четверку, 400 Bad Request говорит о том, что возникла проблема на стороне пользователя. Зачастую сервер отправляет ее, когда появившаяся неисправность не подходит больше ни под одну категорию ошибок. 

Стоит запомнить — код 400 напрямую связан с клиентом (браузером, к примеру) и намекает на то, что отправленный запрос со стороны пользователя приводит к сбою еще до того, как его обработает сервер (вернее, так считает сам сервер). 

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Из-за чего всплывает Bad Request?

Есть 4 повода для возникновения ошибки сервера 400 Bad Request при попытке зайти на сайт:

  1. Некорректно настроенные HTTP-заголовки в запросе со стороны клиента. Некоторые приложения и сайты мониторят заголовки на предмет наличия в них чего-нибудь подозрительного. Если ваш запрос не соответствует ожиданиям сервера, то высока вероятность появления ошибки 400 (но это не всегда вина пользователя).
  2. Такой же сбой появляется, если клиент пытается загрузить на сервер файл слишком большого размера. Это происходит, потому что на большинстве сайтов есть ограничения по размеру загружаемых данных. Причем ограничение может быть как в 2 гигабайта, так и в 600 килобайт.
  3. Еще ошибка 400 появляется, когда пользователь пытается получить доступ к несуществующей странице. То есть в браузер банально ввели ссылку с опечаткой, некорректным доменом или поддоменом.
  4. Устаревшие или измененные куки-файлы. Сервер может воспринять подмену куки-файлов как попытку атаковать или воспользоваться дырой в безопасности. Поэтому такие запросы сходу блокируются.

Читайте также

Ошибка сервера 401

Ошибка 502 Bad Gateway Error

Исправляем ошибку 400 Bad Request на стороне клиента

Так как ошибка 400 в 99 случаев из 100 возникает на стороне клиента, начнем с соответствующих методов. Проверим все элементы, участвующие в передаче запроса со стороны клиента (браузера).

Проверяем адрес сайта

Банальщина, но необходимая банальщина. Перед тем как бежать куда-то жаловаться и предпринимать более серьезные шаги, повнимательнее взгляните на ссылку в адресной строке. Может, где-то затесалась опечатка или вы случайно написали большую букву вместо маленькой. Некоторые части адреса чувствительны к регистру. 

А еще стоит поискать запрашиваемую страницу через поисковик, встроенный в сайт. Есть вероятность, что конкретная страница куда-то переехала, но сервер не может показать подходящий HTTP-код в духе 404 Not Found. Если, конечно, сам сайт работает. 

Сбрасываем параметры браузера

Этот метод срабатывает, если сервер отказывается принимать запросы из-за «битых» куки или других данных. Дело в том, что сайт использует куки-файлы, чтобы хранить информацию о пользователе у него же в браузере. При входе конкретного человека на ресурс, он пытается распознать куки и сравнить информацию с той, что уже есть на сервере.

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

В зависимости от браузера процесс удаления куки-файлов может немного отличаться. В Chrome это работает так:

  • Открываем настройки браузера. 
  • Переходим в раздел «Конфиденциальность и безопасность».
  • Выбираем «Файлы cookie и другие данные».
  • Нажимаем на кнопку «Удалить все».Удаление кукис в Google Chrome

Для чистки cookies можно использовать стороннюю программу в духе CCleaner или CleanMyPC.

Загружаем файл подходящего размера

Если ошибка 400 Bad Request появляется при попытке загрузить на сайт какой-нибудь файл, то стоит попробовать загрузить файл поменьше. Иногда вебмастера ленятся грамотно настроить ресурс, и вместо понятного объяснения вроде «Загружаемые файлы не должны быть размером больше 2 мегабайт» люди получают Bad Request. Остается только гадать, какой там у них лимит. 

Устраняем проблемы, связанные с Windows и сторонним софтом

Помимо браузера, на работу сети могут влиять другие программные продукты (экраны, защищающие от «непонятных подключений»). И вирусы. Да и сама Windows может стать проблемой. Почти любой ее компонент. Поэтому надо бы проделать следующее:

  • Повторно установить NET.Framework. Желательно перед этим удалить предыдущую версию.
  • Установить какой-нибудь приличный антивирус (а лучше два) и запустить глубокую проверку систему. Возможно, подключению и входу на ресурс мешает вредоносная программа.
  • Если у вас уже установлен антивирус, то, наоборот, попробуйте его отключить. Иногда встроенные в них экраны проверки подключений блокируют работу браузера целиком или отдельных страниц. Лучше выдать браузеру больше прав на выполнение своих задач или установить антивирус, который более лояльно относится к установленному на компьютере софту.
  • Еще надо поменять параметры брандмауэра. Его можно разыскать в панели управления Windows. Там надо добавить в список исключений ваш браузер. Тогда брандмауэр не будет мешать подключению к запрашиваемому сайту.
  • Почистить Windows от программного мусора. Можно пройтись приложением CCleaner. 
  • Обновить драйверы для сетевых устройств. 
  • Обновить Windows или просканировать систему на наличие погрешностей в системных компонентах.

Ищем проблему на стороне сервера

Если что-то происходит на стороне ресурса, то это редко заканчивается ошибкой 400. Но все-таки есть несколько сценариев, при которых клиента обвиняют в сбое зря, а настоящая вина лежит на сервере. 

Проверяем требования к HTTP-заголовкам

Пока настраиваешь сайт, несложно допустить ошибку или даже парочку. Возможно, требования к HTTP-заголовком указаны некорректно, и сервер ожидает запросы с ошибками, которые по объективным причинам не может распознать адекватно. Тогда администратору стоит перепроверить ожидаемые заголовки на своем сайте или в приложении. 

Удаляем свежие обновления и плагины

Иногда ошибка 400 Bad Request появляется после обновления CMS или установки новых плагинов. Если у вас она появилась из-за этого, то наиболее логичное решение — откатиться до более ранней версии CMS и удалить все новые плагины. 

Главное, перед этим сделать резервную копию данных. И перед установкой обновлений тоже стоило бы.

Проверяем состояние базы данных

Некоторые сторонние расширения для того же WordPress получают полный доступ к ресурсу и имеют право вносить изменения даже в подключенную базу данных. Если после удаления свежих плагинов ошибка 400 никуда не исчезла и появляется у всех, кто пытается зайти на сайт, стоит проверить, в каком состоянии находится база данных. Нужно вручную проверить все записи на наличие подозрительных изменений, которые могли быть сделаны установленными расширениями.

Исправляем ошибки в коде и скриптах

Ничего из вышеперечисленного не помогло? Тогда осталось проверить свой код и работающие скрипты. Лучше провести дебаггинг вручную и не надеяться на помощь компьютера. Сделать копию приложения или сайта, потом пошагово проверить каждый отрезок кода в поисках ошибок. 

В крайнем случае придется кричать «полундра» и звать на помощь техподдержку хостинга. Возможно, возникли сложности на их стороне. Тогда вообще ничего не надо будет делать. Просто ждать, пока все исправят за вас. 

На этом все. Основные причины появления 400 Bad Request разобрали. Как ее лечить — тоже. Теперь дело за вами. Пользуйтесь полученной информацией, чтобы больше не пришлось мучиться в попытках зайти на нужный ресурс.

Ошибка 400 Bad Request – это код ответа HTTP, который означает, что сервер не смог обработать запрос, отправленный клиентом из-за неверного синтаксиса. Подобные коды ответа HTTP отражают сложные взаимоотношения между клиентом, веб-приложением, сервером, а также зачастую сразу несколькими сторонними веб-сервисами. Из-за этого поиск причины появления ошибки может быть затруднён даже внутри контролируемой среды разработки.

В этой статье мы разберём, что значит ошибка 400 Bad Request (переводится как «Неверный запрос»), и как ее исправить

  • На стороне сервера или на стороне клиента?
  • Начните с тщательного резервного копирования приложения
  • Диагностика ошибки 400 Bad Request
  • Исправление проблем на стороне клиента
    • Проверьте запрошенный URL
    • Очистите соответствующие куки
    • Загрузка файла меньшего размера
    • Выйдите и войдите
  • Отладка на распространённых платформах
    • Откатите последние изменения
    • Удалите новые расширения, модули или плагины
    • Проверьте непреднамеренные изменения в базе данных
  • Поиск проблем на стороне сервера
    • Проверка на неверные заголовки HTTP
    • Просмотрите логи
  • Отладьте код приложения или скриптов

Все коды ответа HTTP из категории 4xx считаются ошибками на стороне клиента. Несмотря на это, появление ошибки 4xx не обязательно означает, что проблема как-то связана с клиентом, под которым понимается веб-браузер или устройство, используемое для доступа к приложению. Зачастую, если вы пытаетесь диагностировать проблему со своим приложением, можно сразу игнорировать большую часть клиентского кода и компонентов, таких как HTML, каскадные таблицы стилей (CSS), клиентский код JavaScript и т.п. Это также применимо не только к сайтам. Многие приложения для смартфонов, которые имеют современный пользовательский интерфейс, представляют собой веб-приложения.

С другой стороны, ошибка 400 Bad Request означает, что запрос, присланный клиентом, был неверным по той или иной причине. Пользовательский клиент может попытаться загрузить слишком большой файл, запрос может быть неверно сформирован, заголовки HTTP запроса могут быть неверными и так далее.

Мы рассмотрим некоторые из этих сценариев (и потенциальные решения) ниже. Но имейте в виду: мы не можем однозначно исключить ни клиент, ни сервер в качестве источника проблемы. В этих случаях сервер является сетевым объектом, генерирующим ошибку 400 Bad Request и возвращающим её как код ответа HTTP клиенту, но возможно именно клиент ответственен за возникновение проблемы.

Важно сделать полный бэкап вашего приложения, базы данных и т.п. прежде, чем вносить какие-либо правки или изменения в систему. Ещё лучше, если есть возможность создать полную копию приложения на дополнительном промежуточном сервере, который недоступен публично.

Подобный подход обеспечит чистую тестовую площадку, на которой можно отрабатывать все возможные сценарии и потенциальные изменения, чтобы исправить или иную проблему без угрозы безопасности или целостности вашего «живого» приложения.

Ошибка 400 Bad Request означает, что сервер (удалённый компьютер) не может обработать запрос, отправленный клиентом (браузером), вследствие проблемы, которая трактуется сервером как проблема на стороне клиента.

Существует множество сценариев, в которых ошибка 400 Bad Request может появляться в приложении. Ниже представлены некоторые наиболее вероятные случаи:

  • Клиент случайно (или намеренно) отправляет информацию, перехватываемую маршрутизатором ложных запросов. Некоторые веб-приложения ищут особые заголовки HTTP, чтобы обрабатывать запросы и удостовериться в том, что клиент не предпринимает ничего зловредного. Если ожидаемый заголовок HTTP не найден или неверен, то ошибка 400 Bad Request – возможный результат.
  • Клиент может загружать слишком большой файл. Большинство серверов или приложений имеют лимит на размер загружаемого файла, Это предотвращает засорение канала и других ресурсов сервера. Во многих случаях сервер выдаст ошибку 400 Bad Request, когда файл слишком большой и поэтому запрос не может быть выполнен.
  • Клиент запрашивает неверный URL. Если клиент посылает запрос к неверному URL (неверно составленному), это может привести к возникновению ошибки 400 Bad Request.
  • Клиент использует недействительные или устаревшие куки. Это возможно, так как локальные куки в браузере являются идентификатором сессии. Если токен конкретной сессии совпадает с токеном запроса от другого клиента, то сервер/приложение может интерпретировать это как злонамеренный акт и выдать код ошибки 400 Bad Request.

Устранение ошибки 400 Bad Request (попробуйте позже) лучше начать с исправления на стороне клиента. Вот несколько советов, что следует попробовать в браузере или на устройстве, которые выдают ошибку.

Наиболее частой причиной ошибки 400 Bad Request является банальный ввод некорректного URL. Доменные имена (например, internet-technologies.ru) нечувствительны к регистру, поэтому ссылка, написанная в смешанном регистре, такая как interNET-technologies.RU работает так же, как и нормальная версия в нижнем регистре internet-technologies.ru. Но части URL, которые расположены после доменного имени, чувствительными к регистру. Кроме случаев, когда приложение/сервер специально осуществляет предварительную обработку всех URL и переводит их в нижний регистр перед исполнением запроса.

Важно проверять URL на неподходящие специальные символы, которых в нем не должно быть. Если сервер получает некорректный URL, он выдаст ответ в виде ошибки 400 Bad Request.

Одной из потенциальных причин возникновения ошибки 400 Bad Request являются некорректные или дублирующие локальные куки. Файлы куки в HTTP – это небольшие фрагменты данных, хранящиеся на локальном устройстве, которые используются сайтами и веб-приложениями для «запоминания» конкретного браузера или устройства. Большинство современных веб-приложений использует куки для хранения данных, специфичных для браузера или пользователя, идентифицируя клиента и позволяя делать следующие визиты быстрее и проще.

Но куки, хранящие информацию сессии о вашем аккаунте или устройстве, могут конфликтовать с другим токеном сессии от другого пользователя, выдавая кому-то из вас (или вам обоим) ошибку 400 Bad Request.

В большинстве случаев достаточно рассматривать только ваше приложение в отношении файлов куки, которые относятся к сайту или веб-приложению, выдающему ошибку 400 Bad Request.

Куки хранятся по принципу доменного имени веб-приложения, поэтому можно удалить только те куки, которые соответствуют домену сайта, сохранив остальные куки не тронутыми. Но если вы не знакомы с ручным удалением определённых файлов куки, гораздо проще и безопаснее очистить сразу все файлы куки.

Это можно сделать разными способами в зависимости от браузера, который вы используете:

  • Google Chrome;
  • Internet Explorer;
  • Microsoft Edge;
  • Mozilla Firefox;
  • Safari.

Если вы получаете ошибку 400 Bad Request при загрузке какого-либо файла, попробуйте корректность работы на меньшем по размеру файле, Это включает в себя и «загрузки» файлов, которые не загружаются с вашего локального компьютера. Даже файлы, отправленные с других компьютеров, считаются «загрузками» с точки зрения веб-сервера, на котором работает ваше приложение.

Попробуйте выйти из системы и войти обратно. Если вы недавно очистили файлы куки в браузере, это приводит к автоматическому выходу из системы при следующей загрузке страницы. Попробуйте просто войти обратно, чтобы посмотреть, заработала ли система корректно.

Также приложение может столкнуться с проблемой, связанной с вашей предыдущей сессией, являющейся лишь строкой, которую сервер посылает клиенту, чтобы идентифицировать клиента при будущих запросах. Как и в случае с другими данными, токен сессии (или строка сессии) хранится локально на вашем устройстве в файлах куки и передаётся клиентом на сервер при каждом запросе. Если сервер решает, что токен сессии некорректен или скомпрометирован, вы можете получить ошибку 400 Bad Request.

В большинстве веб-приложений выход повторный вход приводит к перегенерации локального токена сессии.

Если вы используете на сервере распространённые пакеты программ, которые выдают ошибку 400 Bad Request, изучите стабильность и функциональность этих платформ. Наиболее распространённые системы управления контентом, такие как WordPress, Joomla! и Drupal, хорошо протестированы в своих базовых версиях. Но как только вы начинаете изменять используемые ими расширения PHP, очень легко спровоцировать непредвиденные проблемы, которые выльются в ошибку 400 Bad Request.

Если вы обновили систему управления контентом непосредственно перед появлением ошибки 400 Bad Request, рассмотрите возможность отката к предыдущей версии, которая была установлена, как самый быстрый и простой способ убрать ошибку 400 bad request.

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

Но в некоторых случаях CMS не предоставляют возможности отката к предыдущим версиям. Так обычно происходит с популярными платформами, поэтому не бойтесь, если вы не можете найти простой способ вернуться к использованию старой версии той или иной программной платформы.

В зависимости от конкретной CMS, которую использует приложение, имена этих компонентов будут различаться. Но во всех системах они служат одной и той же цели: улучшение возможностей платформы относительно её стандартной функциональности.

При этом имейте в виду, что расширения могут так или иначе получать полный контроль над системой, вносить изменения в код PHP, HTML, CSS, JavaScript или базу данных. Поэтому мудрым решением может быть удаление любых новых расширений, которые были недавно добавлены.

Даже если удалили расширение через панель управления CMS, это не гарантирует, что внесенные им изменения были полностью отменены. Это касается многих расширений WordPress, которым предоставляется полный доступ к базе данных.

Расширение может изменить записи в базе данных, которые «не принадлежат» ему, а созданы и управляются другими расширениями (или даже самой CMS). В подобных случаях модуль может не знать, как откатить назад изменения, внесенные в записи базы данных.

Я лично сталкивался с такими случаями несколько раз. Поэтому лучшим путём будет открыть базу данных и вручную просмотреть таблицы и записи, которые могли быть изменены расширением.

Если вы уверены, что ошибка 400 Bad Request не связана с CMS, вот некоторые дополнительные советы, которые могут помочь найти проблему на стороне сервера.

Ошибка, которую вы получаете от приложения, является результатом недостающих или некорректных специальных заголовков HTTP, которые ожидает получить приложение или сервер. В подобных случаях нужно проанализировать заголовки HTTP, которые отправляются на сторону сервера.

Почти любое веб-приложение будет вести логи на стороне сервера. Они представляют собой историю того, что делало приложение. Например, какие страницы были запрошены, к каким серверам оно обращалось, какие результаты предоставлялись из базы данных и т.п.

Логи сервера относятся к оборудованию, на котором выполняется приложение, и зачастую представляют собой детали о статусе подключённых сервисов или даже о самом сервере. Поищите в интернете “логи [ИМЯ_ПЛАТФОРМЫ]”, если вы используете CMS, или “логи [ЯЗЫК_ПРОГРАММИРОВАНИЯ]” и “логи [ОПЕРАЦИОННАЯ_СИСТЕМА]”, если у вас собственное приложение, чтобы получить подробную информацию по поиску логов.

Если это не помогло, проблема может быть в исходном коде, который выполняется внутри приложения. Попытайтесь диагностировать, откуда может исходить проблема, отлаживая приложение вручную и параллельно просматривая логи приложения и сервера.

Создайте копию всего приложения на локальном устройстве для разработки и пошагово повторите тот сценарий, который приводил к возникновению ошибки 400 Bad Request. А затем просмотрите код приложения в тот момент, когда что-то пойдёт не так.

Независимо от причины возникновения ошибки, даже если вам удалось исправить её в этот раз, появление в вашем приложении такой проблемы — это сигнал для того, чтобы внедрить инструмент обработки ошибок, который поможет автоматически обнаруживать их и оповещать в момент возникновения.

When a website fails to load, it’s simply annoying. It’s important to understand, though, why that happened so you know how to fix it.

The 4xx family of status codes is the one we’re investigating here as they relate to invalid or corrupt requests from the client. Specifically, we’ll take a closer look at the 400 Bad Request error: what this error means, what causes it as well as some specific steps to fix the issue.

  • What is 400 Bad Request Error?
  • What Causes a 400 Bad Request Error
  • 400 Bad Request Error: What Does It Look Like?
  • How to Fix 400 Bad Request Error

Check out our video guide to fixing 400 errors:

What is a 400 Bad Request Error?

A 400 Bad Request, also known as a 400 error or HTTP error 400, is perceived by the server as a generic client error and it is returned when the server determines the error doesn’t fall in any of the other status code categories.

The key concept to understand here is that the 400 Bad Request error is something that has to do with the submitted request from the client before it is even processed by the server.

The Internet Engineering Task Force (IETF) defines the 400 Bad Request as:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

What Causes the HTTP 400 Bad Request Error?

There are various root causes that can trigger the 400 Bad Request error and, even if this error isn’t specific to any particular browser or OS (operating system), the fixes do vary slightly.

1. URL String Syntax Error

The HTTP error 400 can occur due to incorrectly typed URL, malformed syntax, or a URL that contains illegal characters.

This is surprisingly easy to do by mistake and can happen if a URL has been encoding incorrectly. The following link is an example of a URL containing characters the server won’t be able to process, hence a 400 Bad Request error is triggered.

https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL

Note the extra % character immediately after the word malformed in the URL. A properly encoded space should be %20 and not %%20. This is what the result looks like in the Chrome browser.

An illegal character can also trigger a 400 Bad request error. The following URL contains a { character, which is not allowed. Therefore, it results in the same type of error.

https://twitter.com/share?lang=en&text=Example%20of%20malformed{%20characters%20in%20URL

2. Corrupted Browser Cache & Cookies

Even if the URL is 100% correct, the 400 Bad Request error can still occur because of corrupted files in the browser cache or problems with expired/corrupted browser cookies.

You may have encountered a 400 Bad Request error when trying to access the admin area of your WordPress site some time after your last log in. That’s happening because of the way the cookie handling your login authentication data may have gotten corrupted and can’t successfully authenticate you as a valid user with admin privileges. This will then result in the connection being refused and a 400 Bad Request error is triggered.

3. DNS Lookup Cache

The 400 Bad Request can happen when the DNS data stored locally is out of sync with registered DNS information.

All domain names are aliases for IP addresses. You can think of an IP address as a phone number “always calling” a specific server you want to connect to. When you first visit a website, a process called “name resolution” takes place and that’s when the domain name resolves to the specific IP address of the server.

To speed things up, these details are stored locally on your computer in the local DNS cache so the name resolution process doesn’t have to be done for every single visit for a given website. This is similar to how the browser cache works for HTML, CSS, JavaScript, media, and other files.

4. File Size Too Large

A 400 Bad Request can also occur when you try to upload a file to a website that’s too large for the upload request to be fulfilled. This is strictly related to the file size limit of the server and will vary based on how it has been set up.

Until now, we’ve focused on the 400 Bad Request error being triggered only due to client-side issues.

5. Generic Server Error

This error can sometimes be triggered because of server-side issues as well. Specifically, a 400 status code could indicate a general problem with the server, a server glitch, or other unspecified temporary issues.

If this happens when trying to connect to a third-party website, it’s really outside of your control and your best shot is to try refreshing the browser and check at regular intervals whether the issue has been fixed by the site owners.

One thing you can do to verify the issue is a server-side issue is to try loading the website on different browsers. If you want to go the extra mile, test it on an entirely different machine/device to rule out system-specific problems.

When you can’t connect to the site via any other browsers, computers, operating systems, or other devices then it’s likely to be a server-side issue. If you’d like, you can reach out to the site owner and let them know which OS, browser, and versions you were using when experienced the issue.

400 Bad Request Error: What Does It Look Like?

Most of the time a 400 Bad Request is related to client-side issues. We already saw what a 400 Bad Request error looks like in the Chrome browser.

400 bad request error in Chrome

400 bad request error in Chrome

But what about the other browsers?

400 Bad Request in Firefox

400 bad request error in Firefox

400 bad request error in Firefox

400 Bad Request in Safari

400 bad request error in Safari

400 bad request error in Safari

400 Bad Request in Microsoft Edge

400 bad request error in Microsoft Edge

400 bad request error in Microsoft Edge

As you can see, all browsers return a generic and unhelpful 400 status code message. It seems you’re pretty much left alone for finding a solution to the problem. In Firefox and Safari, it’s not even clear a 400 Bad Request error has occurred at all as the browser window is completely blank!

Fortunately, we’ve put together a series of simple steps you can take to fix the 400 Bad Request error. Let’s take a closer look at each one of these in the next section!

400 Bad Request (Glossary):

The 400 Bad Request Error is an HTTP response status code
that indicates the server was unable to process (understand) the request sent by the client due to incorrect syntax, invalid request message framing, or deceptive request routing.

How to Fix 400 Bad Request Error?

Complete the steps outlined in this section to help diagnose and correct a 400 Bad Request.

The proposed solutions include:

  • 1. Check the Submitted URL
  • 2. Clear Browser Cache
  • 3. Clear Browser Cookies
  • 4. File Upload Exceeds Server Limit
  • 5. Clear DNS Cache
  • 6. Deactivate Browser Extensions

Before digging deeper on the different ways to fix the 400 Bad Request error, you may notice that several steps involve flushing locally cached data.

It’s true that if your computer didn’t cache any files or data at all, there would probably be significantly less connection error issues.

However, the benefits of caching files/data are well documented and the web browsing experience would certainly suffer if caching techniques weren’t used by browsers. When it comes to Edge Caching, for example, you can reduce by more than 50% the time required to deliver full pages to browsers.

It all comes down to a compromise between optimization and user experience, where websites try to load as quickly as possible but can occasionally be prone to errors such as a 400 Bad Request without any warning.

1. Check the Submitted URL

As this is one of the most common reasons for a 400 Bad Request error let’s start with an obvious culprit, the URL string itself. It can be very easy to include unwanted characters in the URL when entering it manually in the browser.

Check that the domain name and specific page you’re trying to access are spelled and typed correctly. Also, make sure they’re separated with forward slashes. If the URL contains special characters, make sure they have been encoded correctly and are legal URL characters.

For long URLs, you might find it easier and less error-prone, to use an online URL encoder/decoder. These type of utilities should also be able to detect illegal characters automatically in the URL as well.

Once you’re sure the URL is correct, try to access it again in the browser. If you’re still getting the 400 Bad Request error it’s time to clear some cache!

2. Clear Browser Cache

If any locally stored website files have been corrupted this can cause a 400 Bad Request error to be returned instead of the expected website content.

This includes all types of files a website needs to properly run such as:

  • HTML
  • JavaScript
  • Text/config files
  • CSS
  • Media (images, videos, audio)
  • Data files (XML, JSON)

These files are stored locally on your computer by the browser when the website is originally visited.

To fix this, the browser cache needs to be cleared.

In Chrome, click on the three-dotted icon on the right-hand corner and select the More Tools > Clear Browsing Data from the popup menu.

Clearing the browser cache menu option

Clearing the browser cache menu option

This will display the Clear browsing data window. In here, you’ll want to make sure the Cached images and files option is checked and then click on the Clear data button to clear the browser cache.

You can also choose to delete recent files for a specific time range via the Time range dropdown. However, to make sure all potentially corrupted files are removed we recommend deleting all locally stored files by selecting the All time option.

Clear browsing data options

Clear browsing data options

If you’re using an alternative browser, check this guide for clearing the browser cache for all the major browsers (Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera).

3. Clear Browser Cookies

If clearing your browser cache didn’t work, then it’s time to delete the cookies too. A single website can use dozens of different cookies. If just one of them is expired or becomes corrupted, then it can be enough to trigger a 400 Bad Request.

To clear your cookies in Chrome, open up the Clear browsing data window by clicking the icon with the three dots in the top-right corner and select More Tools > Clear Browsing Data from the popup menu.

Make sure the Cookies and other site data is checked and select All time for the date range option to delete all current website cookies.

Clear browsing data options (cookies)

Clear browsing data options (cookies)

Once done, try loading the website which returned the 400 Bad Request error again. Assuming the site uses cookies, clearing them out from your browser could fix the issue as it’s often associated with corrupt or expired cookies.

To clear cookies in browsers other than Chrome please read this guide here.

4. File Upload Exceeds Server Limit

If you’re trying to upload a file to a website that’s exceeding the server file size limit, you’ll encounter a 400 Bad Request error.

You can test this out by uploading a smaller file first. If this is successful then the initial file is probably too large and you’ll need to find some way to reduce it before uploading it again.

This will depend on the type of file you’re trying to upload but there are plenty of resources available online that can help to compress large images, video, and audio files.

5. Clear DNS Cache

Another common cause of a 400 Bad Request is when local DNS lookup data becomes either corrupted or out-of-date.

Local DNS data isn’t stored by the browser but by the operating system itself. We have put together a detailed guide to clear the DNS cache for Windows and macOS operating systems.

6. Deactivate Browser Extensions

If you have browser extensions installed that affect website cookies then these could actually be the culprit here. Try temporarily disabling them to see if it makes a difference before trying to connect to the website again.

You may not have considered this could be an issue, but it’s certainly worth a try if you’ve exhausted all other options.

Experiencing a 400 Bad Request error? Check out our detailed guide on how to fix it once and for all! ❌🦊Click to Tweet

Summary

If you’re experiencing a 400 Bad Request error there are several actions you can perform to try and fix the issue.

In the vast majority of possible scenarios, a 400 Bad Request is a client-side issue caused by the submitted request to the server or a local caching issue. The solutions outlined in this article are easy to implement by anyone with minimal technical knowledge. You should be able to get your website working again in no time!

On occasions, though, a 400 Bad Request status code could hint to a generic server issue. This can be quickly diagnosed by testing the given site on different devices. If you suspect this to be a server-side error, there’s not much you can do other than keep trying to load the site at regular intervals and inform the site admin.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Ultimate Guide to Understanding HTTP Status Codes – 400 Series

Thomas

400 series request codes deal with malformed and unserviceable requests from a user-agent. Whenever a 400 series is encountered the problem is usually on the client side.

Issues with a user-agent client can range from requesting resources that are no longer available (by mis-typing a URI) or even the server reacting to requests fitting a security-attack signature.

The most common is the 404 – document not found. 404 Document Not Found is returned when a resource is requested the web-server cannot find:

Google 404 Document Not Found

404 Document not Found when mistyping a URL

Let’s go over the most common and interesting 404 series response codes in a little more detail.

400 – Bad Request

400 Bad Request is (usually) the result of a user-agent sending something in the request a web-server could not process. Let’s generate a 400 Bad Request to understand what can cause this error.

We will go old-school on Linux and use a tool called netcat. Netcat can be used for sending raw data over sockets. After all, HTTP requests are just that – raw text.

First, let’s send a legitimate HEAD Request to google:

HEAD Request from netcat

The web-server responded with 200.

Let’s force a 400 – Bad Request:

Forced Bad Request Generating a 400

We purposfully sent a request the server could not understand – let’s look at the request method used:

mint ~ # nc www.google.com 80
BAD / HTTP/1,1
Host: www.google.com

The web-server could not process the method: BAD

It’s unlikely a modern web browser would send malformed requests like depicted above. However, if you’re using a custom developed HTTP application like a web-scraper, it’s time to debug.

Following the procedures below will resolve most all 400 Bad Request Errors.

1. Check The URL

If clicking on a link it is quite possible the web-author made a typo. Examine the entire URL paying particular attention to the path, document title, and query-string portions.

2. Clear all Cookies and Cache

Clearing the browser cache will solve 80% of 400 Bad Request Codes. Following these steps is a good universal fix for a lot of 400 Status Codes, too.

  1. clear all cookies and browsing history
  2. re-try the request

Let’s see how this is done with Chrome:

  1. Go into Settings 

    Go to Settings

  2. Go to Advanced

    Go to Advanced Options

  3. Click “Clear Browsing Data”

    Clear Browsing Data

  4. Select the following options

    Select The Following Options

Clearing all cookies and browsing history will assure anything cached and/or corrupted (like cookies) are gone. More than likely this will fix your issues with most 400 Bad Request Codes

3. File Upload Size

The problem could very well be a back-end script itself, uploading too large of a file or a file with an incorrect media type.

  1. If the 400 bad request presents itself while uploading a file, try a smaller file.
  2. Make sure the file-type is acceptable. 2.
  3. If uploading an image try both jpeg and png formats.
  4. If an uploading a document usually text files .txt and Microsoft Word files are permitted.

4. Malformed Headers

Malformed headers would be a pretty low-level issue and could very well leave the web-application itself at fault.

Using the HTTPFox plugin with Firefox we can watch the entire HTTP transaction for anything looking out of the ordinary. 

Looking at HTTP Transactions in Firefox

Looks as if I need to clear the cache on my web-browser. Pretty simple to diagnose with HTTPFox.

5. Update Your Web Browser and Disable Plugins

Like anything HTTP goes through versions and revisions. If your browser is out of date it could very well be sending antiquated headers and requests.

Also, try removing or disabling all plug-ins and extensions. Trying the same request in another web browser can assist in isolating issues as well.

6. Check Your Internet Connection

A bad Internet Connection can cause data to be corrupted at lower layers, thus sending malformed data to the web server.

Using a good Internet Speed Test utility can help troubleshoot any issues with an Internet connection. Try running the utility 5 or 6 times for comparison.

Internet Speed Test

7. Try Logging Out

If using a web application with user-based authentication and sessions try logging out and then clearing the browser cache.


401 – Unauthorized

401 Unauthorized is returned when a web server requests credentials for a secured document.

Authorization Required

The HTTP Response will be 200 upon valid credentials being supplied

403 – Forbidden

403 Forbidden is usually one of four things:

  • directory listings are not permitted
  • currently authenticated user does not have sufficient permissions
  • the web-server process has inadequate permissions
  • requesting address has been banned

Directory Listing Not Permitted

HTTP 403 Forbidden

Shows 403 Forbidden when trying to access a directory listing

IIS Showing Directory Permissions are not granted to unauthenticated users. The simplest method is to put an index file in the directory. Otherwise, directory listings to unauthenticated users will need to be explicitly set.

Authenticated User Does Not Have Permissions

The best method in this situation is making a group for all users who need access to a resource. Give this group the necessary permissions at the filesystem level. Then add permitted users to the group.

Web Server Process Does Not Have Sufficient Permissions

Access Denied

We are unable to access the test.php page in the webroot in /var/www/html. So first we need to:

  • check permissions to the webroot:

  • assign the www-data group to the webroot and give read + execute permissions:

     mint# ls -ld /var/www/html/
     drwx------ 3 root root 4096 Nov 24 03:47 /var/www/html/
    

    the /usr/var/html/ directory is owned by the root user and root group with no access to any other user.

    To fix a permissions issue like this, we need to modify permissions to the directory:

     mint# chgrp -R www-data /var/www/html
     mint# chmod 750 /var/www/html
     mint# chmod g+rx /var/www/html/test.php 
     mint html # chmod g-w /var/www/html/test.php 
     mint# ls -ld /var/www/html/
       drwxrw---- 3 root www-data 4096 Nov 24 03:47 /var/www/html/
     mint# ls -l /var/www/html/test.php 
        -rwxr-x--- 1 root www-data 91 Nov 16 06:52 /var/www/html/test.php
    

A little theory on how the problem was fixed:

  1. change the owning group of the webroot to www-data
  2. give proper permissions to the web-root for the www-data group. directory should be read and execute
  3. give read and execute permissions to test.php for the www-data group

For best security practice the www-data group should not have write permissions on files and folders. However, some content management systems or special purpose scripts may need write access by the web-server process

Denying write permissions to files and folders can provide a higher layer of security in the event a web-application flaw is leveraged by an attacker to modify content, delete files, or add files.

Permissions, as mentioned above, are for a production environment. But can be somewhat restrictive for development stages.

Since we took away write permissions to the directory and to test.php only root can add and edit files. This is good in production – we are 100% sure the web-process cannot write to and create files if a script is compromised.

However, this is very impractical for development. In a staging environment, it would be best to put developers in the www-data group. Then give them write permissions to the web-root and all its files. This is a good example of why modern DevOps keeps staging and production segmented.

Another common scenario for a 403 Forbidden Status may be an IP Address or IP Range being banned in a .htaccess file by the server Administrator.

404 – Not Found

404 Not Found means the web-server could not find a requested resource. When encountering a 404 error a few things can be done:

  • check spelling of host, domain, path, and document

  • check case of file and path. Linux and Unix web-servers (unless configured differently) usually distinquish case, with tradition of using all lowercase for each.

  • use Google to find an alternative URL to the resource

  • try getting a cached page from google

Using Advances Google Operators

Google Get All PDF Files

Many times I have been able to locate a document with expired links (resulting in a 404) using a Google query similar to the one above. Listing of Advanced Google Operators

Try Getting the Same Resource From Google’s Cache

Getting Cached Pages From Google

Using advanced Google Operators and Google’s Cache you may be able to find the resource even if it has been taken down.

405 – Method Not allowed

A 405 Method Not Allowed is presented when attempting a request method that is unpermitted by the web-server.

Unpermitted Request To Google

OPTIONS Request Not Allowed

406 – Not Acceptable

406 Not Acceptable will be given when the user-agent and client cannot establish acceptable content/encoding types or character-sets.

When resolving a 406 Status Code using a tool like HTTPFox is necessary.

Header values sent by the client to look over include:

  • Accept:
  • Accept-Charset
  • Accept-Encoding
  • Accept-Languages

A modern web-browser will never experience this issue. If it does, try upgrading your web-browser to later version.

407 – Proxy Authentication Required

407 Proxy Authentication Required will usually mean the user-agent needs to provide credentials to access a proxy server.

Supplying Proxy Credentials in Linux

408 – Request Timeout

This status code will usually result from latency between your computer and the web-server.

To assist in resolving 408 Request Timeout Errors:

  • try another website to make sure it is not the server infrastructure
  • make sure no other downloads are running saturating your bandwidth
  • reconnect to your WiFi
  • reboot your router
  • try an Internet Speed Test

If able to connect to another website fine, it is probably a remote network. If an Internet Speed Test is showing latency the problem could be your ISP or LAN.

Speed Test

Speedtest.net offers a great and free online app for testing Internet connection speeds. The app will check upload speed, download speed, and latency. Speedtest.net Speed Testing App Online

429 – Too Many Requests

429 will usually mean rate limiting has been enabled on the server. Rate limiting will only allow a certain amount of requests in an allotted amount of time.

When recieving 429 – Too Many Requests the user-agent will be blocked for a time period, usually by IP address.

To bypass 429 and 403 restricted errors try using Tor Browser

TOR Browser

TOR Browser can be used obfuscate your IP address

451 – Unavailable for Legal Reasons

451 could be seen when a web-page violates copyrights, trademarks, intellectual property laws, or has been deemed a threat to national security.

Website Seized by US Law Enforcement

Sample of a website seized by US Law Enforcement

Ultimate Guide to Understanding HTTP Status Codes 500 – Internal Service Error. Before delving into a detailed technical discussion of cause behind 500 error code, it is important to understand what the error code 500 represents.

Read More

  • 400
  • Errors
  • HTTP
Thomas

Bash scripting enthusiast who can also cook up a pretty amazing lasagna. If you don’t find me in the datacenter or in deep thought troubleshooting customer tickets, well… You’re probably not looking hard enough!

What is Hypertext Transfer Protocol (HTTP) anyway?

The world wide web, as we know it today, was invented by a scientist at CERN, the European Organization for Nuclear Rese…

Ultimate Guide to Understanding HTTP Status Codes 500 – Internal Service Error

Before delving into a detailed technical discussion of cause behind 500 error code, it is important to understand what t…

Ultimate Guide Understanding HTTP Status Codes – 300 Series

HTTP 300 status codes are reserved for redirects. Most redirects will be transparent to the end-user and are handled ent…

Some Background

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result.
RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

A great amount of applications are using Restful APIs that are based on the HTTP protocol for connecting their clients. In all the calls, the server and the endpoint at the client both return a call status to the client which can be in the form of:

  • The success of API call.
  • Failure of API call.

In both the cases, it is necessary to let the client know so that they can proceed to the next step. In the case of a successful API call they can proceed to the next call or whatever their intent was in the first place but in the case of latter they will be forced to modify their call so that the failed call can be recovered.

RestCase

To enable the best user experience for your customer, it is necessary on the part of the developers to make excellent error messages that can help their client to know what they want to do with the information they get. An excellent error message is precise and lets the user know about the nature of the error so that they can figure their way out of it.

A good error message also allows the developers to get their way out of the failed call.

Next step is to know what error messages to integrate into your framework so that the clients on the end point and the developers at the server are constantly made aware of the situation which they are in. in order to do so, the rule of thumb is to keep the error messages to a minimum and only incorporate those error messages which are helpful.

HTTP defines over 40 standard status codes that can be used to convey the results of a client’s request. The status codes are divided into the five categories presented here:

  • 1xx: Informational — Communicates transfer protocol-level information
  • 2xx: Success -Indicates that the client’s request was accepted successfully.
  • 3xx: Redirection — Indicates that the client must take some additional action in order to complete their request.
  • 4xx: Client Error — This category of error status codes points the finger at clients.
  • 5xx: Server Error — The server takes responsibility for these error status codes.

HTTP & REST

If you would ask me 5 years ago about HTTP Status codes I would guess that the talk is about web sites, status 404 meaning that some page was not found and etc. But today when someone asks me about HTTP Status codes, it is 99.9% refers to REST API web services development. I have lots of experience in both areas (Website development, REST API web services development) and it is sometimes hard to come to a conclusion about what and how use the errors in REST APIs.

There are some cases where this status code is always returned, even if there was an error that occurred. Some believe that returning status codes other than 200 is not good as the client did reach your REST API and got response.

Proper use of the status codes will help with your REST API management and REST API workflow management.

If for example the user asked for “account” and that account was not found there are 2 options to use for returning an error to the user:

  • Return 200 OK Status and in the body return a json containing explanation that the account was not found.

  • Return 404 not found status.
    The first solution opens up a question whether the user should work a bit harder to parse the json received and to see whether that json contains error or not.

  • There is also a third solution: Return 400 Error — Client Error. I will explain a bit later why this is my favorite solution.

It is understandable that for the user it is easier to check the status code of 404 without any parsing work to do.

I my opinion this solution is actually miss-use of the HTTP protocol

We did reach the REST API, we did got response from the REST API, what happens if the users misspells the URL of the REST API – he will get the 404 status but that is returned not by the REST API itself.

I think that these solutions should be interesting to explore and to see the benefits of one versus the other.

There is also one more solution that is basically my favorite – this one is a combination of the first two solutions, he is also gives better Restful API services automatic testing support because only several status codes are returned, I will try to explain about it.

Error handling Overview

Error responses should include a common HTTP status code, message for the developer, message for the end-user (when appropriate), internal error code (corresponding to some specific internally determined ID), links where developers can find more info. For example:

‘{ «status» : 400,
«developerMessage» : «Verbose, plain language description of the problem. Provide developers suggestions about how to solve their problems here»,
«userMessage» : «This is a message that can be passed along to end-users, if needed.»,
«errorCode» : «444444»,
«moreInfo» : «http://www.example.gov/developer/path/to/help/for/444444,
http://tests.org/node/444444»,
}’

How to think about errors in a pragmatic way with REST?
Apigee’s blog post that talks about this issue compares 3 top API providers.

REST API Error Codes

Facebook

No matter what happens on a Facebook request, you get back the 200 status code — everything is OK. Many error messages also push down into the HTTP response. Here they also throw an #803 error but with no information about what #803 is or how to react to it.

Twilio

Twilio does a great job aligning errors with HTTP status codes. Like Facebook, they provide a more granular error message but with a link that takes you to the documentation. Community commenting and discussion on the documentation helps to build a body of information and adds context for developers experiencing these errors.

SimpleGeo

Provides error codes but with no additional value in the payload.

Error Handling — Best Practises

First of all: Use HTTP status codes! but don’t overuse them.
Use HTTP status codes and try to map them cleanly to relevant standard-based codes.
There are over 70 HTTP status codes. However, most developers don’t have all 70 memorized. So if you choose status codes that are not very common you will force application developers away from building their apps and over to wikipedia to figure out what you’re trying to tell them.

Therefore, most API providers use a small subset.
For example, the Google GData API uses only 10 status codes, Netflix uses 9, and Digg, only 8.

REST API Status Codes Subset

How many status codes should you use for your API?

When you boil it down, there are really only 3 outcomes in the interaction between an app and an API:

  • Everything worked
  • The application did something wrong
  • The API did something wrong

Start by using the following 3 codes. If you need more, add them. But you shouldn’t go beyond 8.

  • 200 — OK
  • 400 — Bad Request
  • 500 — Internal Server Error

Please keep in mind the following rules when using these status codes:

200 (OK) must not be used to communicate errors in the response body

Always make proper use of the HTTP response status codes as specified by the rules in this section. In particular, a REST API must not be compromised in an effort to accommodate less sophisticated HTTP clients.

400 (Bad Request) may be used to indicate nonspecific failure

400 is the generic client-side error status, used when no other 4xx error code is appropriate. For errors in the 4xx category, the response body may contain a document describing the client’s error (unless the request method was HEAD).

500 (Internal Server Error) should be used to indicate API malfunction 500 is the generic REST API error response.

Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception. A 500 error is never the client’s fault and therefore it is reasonable for the client to retry the exact same request that triggered this response, and hope to get a different response.

If you’re not comfortable reducing all your error conditions to these 3, try adding some more but do not go beyond 8:

  • 401 — Unauthorized
  • 403 — Forbidden
  • 404 — Not Found

Please keep in mind the following rules when using these status codes:

A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all.

403 (Forbidden) should be used to forbid access regardless of authorization state

A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”). REST APIs use 403 to enforce application-level permissions. For example, a client may be authorized to interact with some, but not all of a REST API’s resources. If the client attempts a resource interaction that is outside of its permitted scope, the REST API should respond with 403.

404 (Not Found) must be used when a client’s URI cannot be mapped to a resource

The 404 error status code indicates that the REST API can’t map the client’s URI to a resource.

RestCase

Conclusion

I believe that the best solution to handle errors in a REST API web services is the third option, in short:
Use three simple, common response codes indicating (1) success, (2) failure due to client-side problem, (3) failure due to server-side problem:

  • 200 — OK
  • 400 — Bad Request (Client Error) — A json with error more details should return to the client.
  • 401 — Unauthorized
  • 500 — Internal Server Error — A json with an error should return to the client only when there is no security risk by doing that.

I think that this solution can also ease the client to handle only these 4 status codes and when getting either 400 or 500 code he should take the response message and parse it in order to see what is the problem exactly and on the other hand the REST API service is simple enough.

The decision of choosing which error messages to incorporate and which to leave is based on sheer insight and intuition. For example: if an app and API only has three outcomes which are; everything worked, the application did not work properly and API did not respond properly then you are only concerned with three error codes. By putting in unnecessary codes, you will only distract the users and force them to consult Google, Wikipedia and other websites.

Most important thing in the case of an error code is that it should be descriptive and it should offer two outputs:

  • A plain descriptive sentence explaining the situation in the most precise manner.
  • An ‘if-then’ situation where the user knows what to do with the error message once it is returned in an API call.

The error message returned in the result of the API call should be very descriptive and verbal. A code is preferred by the client who is well versed in the programming and web language but in the case of most clients they find it hard to get the code.

As I stated before, 404 is a bit problematic status when talking about Restful APIs. Does this status means that the resource was not found? or that there is not mapping to the requested resource? Everyone can decide what to use and where :)

Понравилась статья? Поделить с друзьями:
  • Rest api выдал ошибку wordpress
  • Rest api error codes
  • Rest api error 500
  • Response get error message
  • Response error parse error