Request failed with status code 400
Request failed with status code 400
request failed with status code 400
I am running server in nodejs, while executing the code of server i am getting an error as «(node:7692) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 400 (node:7692) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code».
this is my serverrender.js code
this is my srver.js code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should add a catch to the get call:
You need to enclose the opening parentheses of the config variable.
Error: Request failed with status code 400. Differences between sending in POSTMAN and in the application
In POSTMAN it works:
In the function submit method POST, when the form is submit, it does not work. I have error:
Error: Request failed with status code 400 at createError (createError.js?2d83) at settle (settle.js?467f) at XMLHttpRequest.handleLoad (xhr.js?b50d)
In tab Network in response I have:
Login
What are the differences between sending in POSTMAN and in the application? Contents of the body convert to a string?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Axios handles error differently.
To find out what really is the issue.
You should use error.request to check if the request you made has error
and use error.response to get the error feedback from the server
The code is stating in the Content-Type that the body will be URL string encoded, but in the body it is given a JavaScript object. It doesn’t seem like the Axios client turns that body object into a url-encoded value (ie from
Localhost:3000/api/products 404 Error You did not create res.get(«/api/products») on server.js or you did not set the proxy. check below for proxy setting.
Proxy error: could not proxy request /api/products Check this:
AxiosError : Request failed with status code 400 (in React JS)
I am trying to post comments using axios. When I submit my datas entered in the form, I see this error in the console :
Here is my code :
Have a look on my server :
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You’re not sending anything to your API. CommentsAPI.create(YOUR COMMENT HERE)
Also, in your server you will need to return helpful error message. Like ‘Hey, there is no message, please send a message in the payload’. That will help you understand better what’s going on.
For anyone else, who is facing the same issue, try changing your get http request to post, if you are sending data from body that has a list. Hope this helps.
If you receive a 400 (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_client_errors), it means that the sever received your request but the content was not valid. Read the documentation of the API to be sure you send the correct payload.
By default, if Axios receives something other than a 2xx, it will throw an exception
Request failed with status code 400 with axios
I am trying to use the login API I made using node, however, whenever I call the API using Axios, it gives me a request failed in the console.
This is how I use axios to call my method:
And this is my login page and console :
This is my backend configuration:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
please try this
well, I do not know how is the backend configured, but you could start by stringyfing yow body
If that does not do any change, then change the header instead
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
400 Bad Request: The request cannot be fulfilled due to bad syntax.
In this case, your client sent you an XML payload that had an invalid zip code, which is a form of invalid syntax; therefore, sending a 400 Bad Request is an appropriate error code to return in this situation.
In addition, Wikipedia cites RFC-4918 as a resource on this topic. From this document, you’ll find the following information:
Servers MAY reject questionable requests (even though they consist of well-formed XML), for instance, with a 400 (Bad Request) status code and an optional response body explaining the problem.
Since your request is well-formed (the XML isn’t bad, it just contains semantically incorrect information) you may reject the content with status code 400. The word *may* suggests that there are other options.
While you might be tempted to use status code 422, this would not be correct in this situation, since the invalid zip code does not meet the criteria to be a semantic error. Read below.
422 Unprocessable Entity (WebDAV; RFC 4918): The request was well-formed but was unable to be followed due to semantic errors.
Syntax errors occur during the parsing of input code, and are caused by grammatically incorrect statements. Typical errors might be an illegal character in the input, a missing operator, two operators in a row, two statements on the same line with no intervening semicolon, unbalanced parentheses, a misplaced reserved word, etc.
Semantic errors occur during the execution of the code, after it has been parsed as grammatically correct. These have to do not with how statements are constructed, but with what they mean. Such things as incorrect variable types or sizes, nonexistent variables, subscripts out of range, and the like, are semantic errors.
Your invalid zip code is neither a syntax error nor a semantic error; thus, it’s reasonable to rule out status code 422 as an option.
To answer your question, status code 400 is appropriate; however, you may have other options as well.
HTTP 400 Bad Request (Request Header too long) responses to HTTP requests
When an HTTP request that needs Kerberos authentication is sent to a website that’s hosted on Internet Information Services (IIS) and is configured to use Kerberos authentication, the HTTP request header would be very long. This article helps you work around the HTTP 400 error that occurs when the HTTP request header is too long.
Original product version: В Windows Server 2016
Original KB number: В 2020943
Symptoms
An HTTP request that needs Kerberos authentication is sent from a browser to a website that’s hosted on IIS. The website is configured to use Kerberos authentication. However, instead of receiving the expected webpage, you receive an error message that resembles the following one:
This response could be generated by any HTTP request that includes Windows Remote Management (WinRM).
Cause
This issue may occur if the user is a member of many Active Directory user groups.
The HTTP request to the server contains the Kerberos token in the WWW-Authenticate header. The header size increases together with the number of user groups. If the HTTP header or packet size increases past the limits that are configured on the server, the server may reject the request and send an error message as the response.
Workaround 1: Decrease the number of Active Directory groups
Decrease the number of Active Directory groups that the user is a member of.
Workaround 2: Set MaxFieldLength and MaxRequestBytes registry entries
Increase the settings for the MaxFieldLength and the MaxRequestBytes registry entries on the server so that the user’s request headers don’t exceed these values. To determine the appropriate settings, use the following calculations:
Calculate the size of the user’s Kerberos token by using the formula described in the following article:
Problems with Kerberos authentication when a user belongs to many groups.
Set the value of MaxFieldLength and MaxRequestBytes on the server to 4/3 * T bytes, where T is the user’s token size in bytes. HTTP encodes the Kerberos token by using base64 encoding.
This replaces every three bytes in the token with four base64-encoded bytes. Changes that are made to the registry do not take effect until you restart the HTTP service. Additionally, you may have to restart any related services, such as IIS services.
Depending on your application environment, you might also work around this problem by configuring the website to use Windows NT LAN Manager (NTLM) instead of Kerberos. Some application environments require Kerberos authentication to be used for delegation. We consider Kerberos authentication to be more secure than NTLM. And we recommend that you don’t disable Kerberos authentication before you consider the security and delegation ramifications.
More information
By default, there is no MaxFieldLength registry entry. This entry specifies the maximum size limit of each HTTP request header. The MaxRequestBytes registry entry specifies the upper limit for the total size of the Request line and the headers. Typically, this registry entry is configured together with the MaxRequestBytes registry entry. If the MaxRequestBytes value is lower than the MaxFieldLength value, the MaxFieldLength value is adjusted. In large Active Directory environments, users may experience logon failures if the values for both these entries aren’t set to a sufficiently high value.
For IIS 6.0 and later, the MaxFieldLength and MaxRequestBytes registry keys are located at the following sub key:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters
Set the key values as shown in the following table:
Name | Value Type | Value Data |
---|---|---|
MaxFieldLength | DWORD | (4/3 * T bytes) + 200 |
MaxRequestBytes | DWORD | (4/3 * T bytes) + 200 |
You can also set the registry keys to their maximum values, as shown in the next table. Consider all potential security ramifications before you make any changes to the registry settings.
Name | Value Type | Value Data |
---|---|---|
MaxFieldLength | DWORD | 65536 (Dec) or 10000 (Hex) |
MaxRequestBytes | DWORD | 16777216 (Dec) or 1000000 (Hex) |
Changing these registry keys should be considered to be extremely dangerous. These keys allow larger HTTP packets to be sent to IIS. This, in turn, may cause Http.sys to use more memory. Therefore, such changes can increase the computer’s vulnerability to malicious attacks.
If MaxFieldLength is set to its maximum value of 64 KB, the MaxTokenSize registry value should be set to 3/4 * 64 = 48 KB. For more information about the MaxTokenSize setting, see Problems with Kerberos authentication when a user belongs to many groups.
Getting 400 error Bad request using axios
I am using axios and getting a 400 bad request error. I am using react-redux and trying to send a post request to localhost:3000/posts. Here is the code that I am using.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
i was also getting this error, the issue was not with server or with axios or proxy url. The issue was i wasn’t sending the correct data from my react application. For Example i supposed to send:
what i was sending is:
this caused api don’t understand name field, as i provided email as the key in api.
so if you are still facing the issue try to check if you are sending the correct data.
For every post request, the client first sends an OPTIONS request to check whether the server is ready to accept the connection. You should also allow the server to accept options request. If you have not allowed use the below lines in case of node server
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
request failed with status code 400
I am running server in nodejs, while executing the code of server i am getting an error as «(node:7692) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 400 (node:7692) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code».
this is my serverrender.js code
this is my srver.js code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should add a catch to the get call:
You need to enclose the opening parentheses of the config variable.
400 vs 422 for Client Error Request
I’ve read a lot of posts and articles regarding proper http status code to return for client request error. Others suggest to use 400 as it has been redefined in RFC 7231 though I’m not sure if the example given covers all the client error in my mind because the examples are syntactic.
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).
I did find this statement in the Appendix B of the rfc 7231:
The 400 (Bad Request) status code has been relaxed so that it isn’t
limited to syntax errors. (Section 6.5.1)
Does this mean that I can consider any type of client error a bad request? Would it be better to use 400 for client requests and just specify a more specific error in the message?
On the other hand, others say that it’s better to use 422 (Unprocessable Entity). While this is more focused on semantics, it’s only listed in [RFC 4918][2] which is a webDAV extension for http/1.1
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
Can I use this webDAV extension codes to handle my http requests? In the case of 422, can I use it even though it’s not in the core http codes.
Should I use 400 or 422 for my client error?
Here are the possible client error I have in mind:
Any informative response will be highly appreciated. Thanks a lot, guys!
Update: I checked google api errors and they are not using 422. On the other hand, Twitter uses 422. I’m more confused than ever >. Follow
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
request failed with status code 400
I am running server in nodejs, while executing the code of server i am getting an error as «(node:7692) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 400 (node:7692) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code».
this is my serverrender.js code
this is my srver.js code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should add a catch to the get call:
You need to enclose the opening parentheses of the config variable.
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
Which status code is correct 404 or 400 and when to use either of these?
What is the status code should return when an object inside my resource is not available?
What should be the response code if the scheme with id 15 does not exist?400 or 404?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I don’t think 404 is suitable for this situation if the request has been performed to a URL that points to a resource that does exist. The problem is in the payload, so 404 has nothing to do with it.
The syntax of the JSON document is valid, so 400 is not suitable either.
What you have is an unprocessable entity due to invalid data, so 422 would be the best alternative here. Keep reading for a more detailed explanation.
Not found and Bad request
Assuming that the request has been performed to a URL that locates a valid resource (that is, a resource that exists), returning 404 is not suitable for this situation and it may yield misunderstanding:
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.
Returning 400 with a descriptive message in the payload would be suitable for this situation if the JSON was malformed, but that’s not the case:
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).
Unprocessable entity
As a matter of fact, what you have is an entity that cannot be processed by the server due to invalid data. So returning 422 and details about the error in the response payload would be the most suitable approach for this situation:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Just read JSON when it says XML.
You also may find this answer helpful.
Problem details for HTTP APIs
HTTP status codes are sometimes not sufficient to convey enough information about an error to be helpful. The RFC 7807 defines simple JSON and XML document formats to inform the client about a problem in a HTTP API.
It also defines the application/problem+json and application/problem+xml media types.
Picking the right 4xx status code
The following diagram (extracted from this page) is pretty insightful when it comes to picking the most suitable 4xx status code. Hopefully it will help you:
What is the status code should return when an object inside my resource is not available?
Michael Kropat put together a pretty good flowchart for choosing an HTTP status code.
The first step is to determine whether or not you have an error at all. It’s perfectly reasonable for resource schema to include optional elements. If that’s appropriate for your circumstances, then just use a 200 and call it a day.
On the other hand, if it is an error, you now need to evaluate the cause of the fault.
If the problem stems from the request, then you should be looking at entries in the 4xx class of status code.
The 4xx (Client Error) class of status code indicates that the client seems to have erred.
These are all variations of a problem with the HTTP Request itself; the client shouldn’t have requested that resource, or the client needed to include different information in the request, or. lots of different variations spelled out by RFC 7231.
The heuristic here is that the client can fix things by sending a different request.
On the other hand, if the request was fine, but the server can’t respond correctly right now, then you should be looking at the 5xx class
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
The 5xx class is much smaller; 500 is almost always the correct choice, the protocol doesn’t care very much about communicating the details to the client because there’s nothing the client can to address a server issue.
My best guess, from your example, is that you should either be sending a 500 response with a payload that contains «an explanation of the error situation», or you should be sending a 200 response with a payload that includes the representation of the resource, even if that representation doesn’t include all of the optional elements.
Исправление ошибки 400 Bad request
400 bad request error – одна из самых популярных проблем, с которой может столкнуться абсолютно любой пользователь, проводящий много времени на просторах интернета. В отличии от ошибки 500, которую мы недавно описывали, данная неприятность, характеризуется следующими особенностями:
Естественно, что мы постараемся помочь нашим читателям и с решением этой проблемы.
Что такое 400 bad request?
Попробуем узнать на официальном сайте операционной системы Windows, что именно обозначает данная неприятность, и как ее исправлять. В перечне возможных проблем находим перевод «routebuildservice 400 bad request – ошибочный запрос. И все. То есть, ребята из Microsoft не хотят помогать в данной ситуации. Ну и ладно – зато мы знаем, как исправить 400 bad request.
400 bad request error – методика исправления
Одной из особенностей данной неприятности является возможность возникновения какой-либо ошибки со стороны владельца сайта или интернет-провайдера. К сожалению, но при таком варианте от пользователя совершенно ничего не зависит. Конечно, компания с хорошей репутацией всегда старается предупреждать своих клиентов о возникновении подобных неприятностей. Но, как показывает практика, в нашей стране делается это очень редко. Поэтому рекомендации для пользователя будут такие – постараться самостоятельно получить требуемую информацию:
Если проблема возникает не по вине удаленного сервера, то следует внимательно еще раз перечитать сообщение, возникающее на экране. Ели оно выглядит так — 400 bad request request header or cookie too large, то решению очень простое:
Заключительный этап, если предыдущие шаги не помогли решить поставленную задачу, касается изменения настроек используемого антивирусного ПО и брандмауэра Windows. Что требуется сделать, чтобы окончательно решить ситуацию с 400 bad request error:
Проблема решена. Данная неприятность, действительно, очень особенная. Поэтому не стоит долго искать ответа на вопрос — 400 bad request: что это означает, — а сразу приступать к лечению.
Один из эффективных способов борьбы с ошибкой 400 можно увидеть на тематическом видео — обязательно посмотрите:
SSRS error message: The request failed with HTTP status 400: Bad Request
An admin updated the dev and test servers by adding Report Viewer 2012 for me.
I have no access to the test server, but am admin on the dev server. I can work with someone who has admin access to the test server, but I will need to know what to look for.
My SSRS reports deployed from Visual Studio 2012 were converted to Microsoft.ReportViewer.WebForms 11.0 from version 10.0.
These reports work just find on my dev server, but when my QA tester uses the report, the first time the page shows the error «The request failed with HTTP status 400: Bad Request.»
Note that no report is loaded by default.
Once we request a report, this report shows up properly and the error message disappears.
I am trying to remove this initial error message, as it is confusing for the end user.
Does anybody have any idea?
Thanks in advance!
Below is the code as shown by developer tools.
CORS Errors only with 400 bad request react fetch request
I’m trying to make ‘POST’ request in react but i’m getting a few problems regarding CORS. I was just following what console says and fix them in server side [which is PHP ] and client side everything works fine when the status is 200 but when status 400 it shows
login:1 Failed to load http://192.168.0.102/API/: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
I’ve tried to add mode: ‘no-cors’ but that’s doesn’t work it shows
Uncaught (in promise) SyntaxError: Unexpected end of input
Server Side ‘PHP Slimframework’ headers:
Client Side
src/actions/userActions.js
src/components/layout.js
here screenshot getting this error only with bad request like 400
Please let me know if I miss out any information.
If this has already been asked, I would greatly appreciate if you are able to point me in the right direction.
Error: Request failed with status code 400 in react-native with axios
I’m getting err: request failed with status code 400. What am I doing wrong here?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
using qs and changing the headers solved my problem.
Good that you managed to solve, for future reference, if you have a 400 Bad Request error, i found really useful to print the error.response.data for more meaningful error messages.
Not the answer you’re looking for? Browse other questions tagged react-native or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
HTTP response status codes
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:
The below status codes are defined by section 10 of RFC 2616. You can find an updated specification in RFC 7231.
Note: If you receive a response that is not in this list, it is a non-standard response, possibly custom to the server’s software.
Information responses
This interim response indicates that the client should continue the request or ignore the response if the request is already finished.
This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.
This code indicates that the server has received and is processing the request, but no response is available yet.
This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.
Successful responses
The request succeeded. The result meaning of «success» depends on the HTTP method:
The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.
This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status.
There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones.
Tells the user agent to reset the document which sent this request.
This response code is used when the Range header is sent from the client to request only part of a resource.
Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
Used inside a response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
Redirection messages
The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.)
The URL of the requested resource has been changed permanently. The new URL is given in the response.
This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
The server sent this response to direct the client to get the requested resource at another URI with a GET request.
This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.
The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
Client error responses
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).
Although the HTTP standard specifies «unauthorized», semantically this response means «unauthenticated». That is, the client must authenticate itself to get the requested response.
This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.
The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource.
This response is sent when the web server, after performing server-driven content negotiation, doesn’t find any content that conforms to the criteria given by the user agent.
This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
This response is sent when a request conflicts with the current state of the server.
This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for «limited-time, promotional services». APIs should not feel compelled to indicate resources that have been deleted with this status code.
Server rejected the request because the Content-Length header field is not defined and the server requires it.
The client has indicated preconditions in its headers which the server does not meet.
Request entity is larger than limits defined by server. The server might close the connection or return an Retry-After header field.
The URI requested by the client is longer than the server is willing to interpret.
The media format of the requested data is not supported by the server, so the server is rejecting the request.
The range specified by the Range header field in the request cannot be fulfilled. It’s possible that the range is outside the size of the target URI’s data.
This response code means the expectation indicated by the Expect request header field cannot be met by the server.
The server refuses the attempt to brew coffee with a teapot.
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
The request was well-formed but was unable to be followed due to semantic errors.
The resource that is being accessed is locked.
The request failed due to failure of a previous request.
Indicates that the server is unwilling to risk processing a request that might be replayed.
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).
The origin server requires the request to be conditional. This response is intended to prevent the ‘lost update’ problem, where a client GET s a resource’s state, modifies it and PUT s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
The user has sent too many requests in a given amount of time («rate limiting»).
The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.
The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
Server error responses
The server has encountered a situation it does not know how to handle.
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
This error response is given when the server is acting as a gateway and cannot get a response in time.
The HTTP version used in the request is not supported by the server.
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
The server detected an infinite loop while processing the request.
Further extensions to the request are required for the server to fulfill it.
Indicates that the client needs to authenticate to gain network access.
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
Как исправить ошибку 400 Bad или Invalid Request HTTP?
Связь между клиентским браузером и веб-сервером может иметь разные типы проблем. Веб-сервер возвращает коды состояния HTTP 4xx всякий раз, когда возникают ошибки при обработке запроса, полученного от браузера. Веб-сервер отправляет HTTP-ответ 400 Bad или Invalid Request, если он не может обработать запрос из клиентского браузера. Обычно это происходит из-за неверного синтаксиса запроса.
Для конечного пользователя получение этой ошибки при доступе к важному веб-сайту может быть довольно неприятным. Вы увидите коды ответа HTTP в браузере из-за сложной взаимосвязи между сервером веб-сайта, пользовательскими устройствами и сторонними службами. Таким образом, может быть сложно определить настоящую причину проблемы, даже если у вас есть контролируемая среда. Однако в большинстве ситуаций довольно легко разобраться в истинной первопричине.
Узнайте больше о том, что такое HTTP, о структуре HTTP-запроса и ответа.
Как исправить ошибку 400 Bad или Invalid Request HTTP?
Вот что вы можете сделать, чтобы исправить 400 неверных или недопустимых ошибок запроса.
A. Для обычных пользователей
Если вы обычный пользователь Интернета и получаете ошибку 400 в браузере, следуйте приведенным ниже решениям.
1. Обновите страницу.
Если у вас есть проблемы с доступом к странице, возможно, стоит попробовать обновить ее. В большинстве случаев HTTP-ошибка 400 Bad or Invalid Request является временной. В большинстве браузеров вы можете нажать клавишу F5 для обновления страницы. Если это не решит вашу проблему сразу, обновите страницу два или три раза, иногда может работать.
Обновить страницу в Chrome Chrome
2. Проверьте свой URL.
Если вы вводите URL-адрес в адресной строке, есть вероятность сделать орфографическую ошибку. Ошибка HTTP 400 Bad или Invalid Request может произойти из-за неправильного ввода URL. Также возможно, что в ссылке указан неверный URL или указан неправильный URL страницы, добавленной в закладки.
Проверьте адрес вручную и посмотрите, нет ли явных ошибок. Если вы не уверены в правильности URL-адреса страницы, попробуйте найти его в результатах поиска Google. У вас могут быть некоторые ключевые слова, которые могут быть связаны с веб-страницей. Выполните поиск по странице с использованием уникальных ключевых слов, чтобы повысить ваши шансы найти страницу.
3. Удалите файлы cookie и кеш.
Ошибка HTTP 400 Bad или Invalid Request может произойти, если ваши файлы cookie устарели или повреждены. Некоторые расширения браузера могут изменять файлы cookie и вызывать ошибки. Итак, в вашем браузере поврежденная версия кеша. Попробуйте очистить файлы cookie и кеш вашего сайта. После очистки кеша страницы могут загружаться немного медленнее, потому что вашему браузеру потребуется перестроить кеш с часто используемыми данными. Но это могло помочь решить проблему.
Помните, что при очистке файлов cookie вам может потребоваться повторно ввести данные для входа на все веб-сайты. Для очистки кеша и файлов cookie для каждого веб-браузера необходимы разные процедуры. Как правило, нажатие «Command + Shift + Delete» на Mac и «Control + Shift + Delete» в Windows будет работать в браузерах Chrome и Firefox.
Подробнее об очистке истории просмотров в популярных браузерах.
4. Очистить DNS
На вашем компьютере могут быть устаревшие записи DNS, и это может вызвать ошибки. Вы можете очистить DNS и проверить, решает ли это проблему с ошибкой 400 HTTP. Это легко сделать и не вызовет нежелательных проблем.
Узнайте подробную информацию о том, как очистить DNS в Windows и Mac.
5. Проверьте размер файла при загрузке.
Ошибка HTTP 400 Bad или Invalid Request может произойти, когда вы пытаетесь загрузить большой файл. Сначала проверьте разрешенный размер файла для загрузки. Если ваш файл больше, вы можете разделить его с помощью утилиты разделения файлов и загружать отдельные части файла.
6. Проверьте другие веб-сайты.
Если вы продолжаете получать ошибку HTTP 400 Bad или Invalid Request при попытке открыть веб-страницу, вам следует проверить, происходит ли это также с другими веб-сайтами. Если ошибка появляется снова, возможно, проблема с сетевыми устройствами на вашем компьютере. На компьютере с Windows запустите программу диагностики сети, чтобы устранить проблему с подключением. На Mac может потребоваться отключить и снова подключить устройство.
Вы также можете обратиться к поставщику услуг Интернета, чтобы узнать, могут ли они решить проблему.
7. Перезагрузите свои устройства.
Это может быть хит и промах. Однако перезагрузка сетевого оборудования и компьютера может помочь вам исправить ошибку HTTP 400 Bad или Invalid Request.
Б. Для разработчиков
Если вы разработчик, вы можете получить ошибку 400 HTTP при тестировании собственного приложения. Следуйте приведенным ниже параметрам, чтобы исправить ошибку.
8. Исправьте недопустимые заголовки HTTP.
Иногда проверка деталей HTTP-заголовка может дать подсказку об ошибке подключения. Вы можете просмотреть детали HTTP-заголовка с помощью одного из бесплатных инструментов в Интернете. Хотя это легко сделать для разработчиков, для не разработчиков это может быть довольно сложно.
9. Проверьте журналы сервера.
Веб-серверы обычно ведут журналы на стороне сервера для каждого запроса, отправляемого клиентом. Журнал может содержать такую информацию, как подключенное приложение, запрошенные страницы, IP-адрес и другую соответствующую информацию о запросах. Журналы сервера часто определяют причину сбоя и указывают статус обработки. Изучая журналы сервера, разработчики и администраторы могут легко определить причину проблем HTTP.
Если у вас нет доступа к файлам журнала сервера, запросите доступ у вашего хостинг-провайдера.
10. Сценарии отладки или код приложения
Если вы получаете сообщение об ошибке в пользовательских приложениях, это может быть связано с плохо написанным кодом в приложении. Разработчикам необходимо вручную отлаживать приложение и проверять журналы сервера для выявления потенциальных проблем.
Наличие хорошей системы управления ошибками может эффективно помочь разработчикам устранить ошибку HTTP 400 Bad или Invalid Request. Даже если ошибки случаются, вы можете обнаружить их автоматически. Например, аэродинамический тормоз — хорошая система мониторинга ошибок, предлагающая обновления в реальном времени. У него отличная панель инструментов, которая предлагает круглосуточные обновления о состоянии вашего веб-приложения. С помощью настраиваемого фильтра ошибок вы можете получать обновления о наиболее важных ошибках.
Заключение
Как объяснялось выше, ошибка 400 происходит из-за отправки неверного запроса на сервер. Это могло быть связано с загрузкой файла или повреждением файлов cookie браузера. Следуйте приведенным выше решениям, и мы надеемся, что одно из них поможет вам решить проблему. Если проблема не исчезнет, это также может быть связано с дополнительными сторонними факторами между вашим браузером и сервером. Подождите некоторое время и попробуйте позже получить доступ к веб-страницам.
В пользовательских приложениях разработчики могут выполнять пошаговый процесс отладки, чтобы найти реальную проблему.
HTTP header 400 bad request response
I’m trying to test writing correct HTTP headers to understand the syntax. Here I’m trying to PUT some text into httpbin.org/put and I expect the response body content to be the same.
However I’m getting the following bad request 400 response:
What syntactical errors have I done? NOTE: newlines are \r\n not \n in the request.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Apparently the correct syntax goes like this for PUT:
I believe I didn’t say much on how I connected to httpbin.org; it was via sockets in C. So the connection was already established before sending the header + message.
You miss the destination url following the PUT verb, the first line must be:
This will probably also fail, you need one of their handler urls so they know what to reply with:
The general form of the first line, or Request Line, in an HTTP request is as follows:
Where for your example, the method is PUT. Including an absolute URL (so, starting with http:// or https:// is only necessary when connecting to a proxy, because the proxy will then attempt to retrieve that URL, rather than attempt to serve a local resource (as found by the path component).
Hope that helped. Consult the HTTP 1.1 RFC (2616), section 5.1 for more information and the official definitions.
request failed with status code 400
I am running server in nodejs, while executing the code of server i am getting an error as «(node:7692) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 400 (node:7692) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code».
this is my serverrender.js code
this is my srver.js code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should add a catch to the get call:
You need to enclose the opening parentheses of the config variable.
Response code 400 or 403 for POST Restful APIs
I am designing a POST Restful API, where I have a situation that I have to authorize a user based upon one of the element provided in the request body. For eg.
So the user making POST request should be authorized to work on division 1. I cannot authorize the user without getting request body.
Also is it okay to do something like :
[EDIT] we preferred not to use 422 error code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
When in doubt, just take a look at the RFC
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
422 Unprocessable Entity (WebDAV; RFC 4918)
The request was well-formed but was unable to be followed due to semantic errors.
That is what I usually use in situations like this.
Again, I don’t think either 400 or 403 make a good case here. Specifically for this situation, 401 exists
Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.
Error: Request failed with status code 400. Differences between sending in POSTMAN and in the application
In POSTMAN it works:
In the function submit method POST, when the form is submit, it does not work. I have error:
Error: Request failed with status code 400 at createError (createError.js?2d83) at settle (settle.js?467f) at XMLHttpRequest.handleLoad (xhr.js?b50d)
In tab Network in response I have:
Login
What are the differences between sending in POSTMAN and in the application? Contents of the body convert to a string?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Axios handles error differently.
To find out what really is the issue.
You should use error.request to check if the request you made has error
and use error.response to get the error feedback from the server
The code is stating in the Content-Type that the body will be URL string encoded, but in the body it is given a JavaScript object. It doesn’t seem like the Axios client turns that body object into a url-encoded value (ie from
Localhost:3000/api/products 404 Error You did not create res.get(«/api/products») on server.js or you did not set the proxy. check below for proxy setting.
Proxy error: could not proxy request /api/products Check this:
400 vs 422 for Client Error Request
I’ve read a lot of posts and articles regarding proper http status code to return for client request error. Others suggest to use 400 as it has been redefined in RFC 7231 though I’m not sure if the example given covers all the client error in my mind because the examples are syntactic.
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).
I did find this statement in the Appendix B of the rfc 7231:
The 400 (Bad Request) status code has been relaxed so that it isn’t
limited to syntax errors. (Section 6.5.1)
Does this mean that I can consider any type of client error a bad request? Would it be better to use 400 for client requests and just specify a more specific error in the message?
On the other hand, others say that it’s better to use 422 (Unprocessable Entity). While this is more focused on semantics, it’s only listed in [RFC 4918][2] which is a webDAV extension for http/1.1
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400 (Bad Request)
status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
Can I use this webDAV extension codes to handle my http requests? In the case of 422, can I use it even though it’s not in the core http codes.
Should I use 400 or 422 for my client error?
Here are the possible client error I have in mind:
Any informative response will be highly appreciated. Thanks a lot, guys!
Update: I checked google api errors and they are not using 422. On the other hand, Twitter uses 422. I’m more confused than ever >. Follow
Как исправить ошибку 400 Bad или Invalid Request HTTP?
Связь между клиентским браузером и веб-сервером может иметь разные типы проблем. Веб-сервер возвращает коды состояния HTTP 4xx всякий раз, когда возникают ошибки при обработке запроса, полученного от браузера. Веб-сервер отправляет HTTP-ответ 400 Bad или Invalid Request, если он не может обработать запрос из клиентского браузера. Обычно это происходит из-за неверного синтаксиса запроса.
Для конечного пользователя получение этой ошибки при доступе к важному веб-сайту может быть довольно неприятным. Вы увидите коды ответа HTTP в браузере из-за сложной взаимосвязи между сервером веб-сайта, пользовательскими устройствами и сторонними службами. Таким образом, может быть сложно определить настоящую причину проблемы, даже если у вас есть контролируемая среда. Однако в большинстве ситуаций довольно легко разобраться в истинной первопричине.
Как исправить ошибку 400 Bad или Invalid Request HTTP?
Вот что вы можете сделать, чтобы исправить 400 неверных или недопустимых ошибок запроса.
A. Для обычных пользователей
Если вы обычный пользователь Интернета и получаете ошибку 400 в браузере, следуйте приведенным ниже решениям.
1 Обновите страницу
Если у вас есть проблемы с доступом к странице, возможно, стоит попробовать обновить ее. В большинстве случаев HTTP-ошибка 400 Bad или Invalid Request является временной. В большинстве браузеров вы можете нажать клавишу F5 для обновления страницы. Если это не решит вашу проблему немедленно, иногда может сработать обновление страницы два или три раза.
Обновить страницу в Chrome Chrome
2 Проверьте свой URL
Если вы вводите URL-адрес в адресной строке, есть вероятность сделать орфографическую ошибку. Ошибка HTTP 400 Bad или Invalid Request может произойти из-за неправильного ввода URL. Также возможно, что в ссылке указан неверный URL-адрес или неверный URL-адрес страницы, добавленной в закладки.
Проверьте адрес вручную и посмотрите, нет ли явных ошибок. Если вы не уверены в правильности URL-адреса страницы, попробуйте найти его в результатах поиска Google. У вас могут быть некоторые ключевые слова, которые могут быть связаны с веб-страницей. Выполните поиск по странице с использованием уникальных ключевых слов, чтобы повысить ваши шансы найти страницу.
3 Удаление файлов cookie и кеша
Ошибка HTTP 400 Bad или Invalid Request может произойти, если ваши файлы cookie устарели или повреждены. Некоторые расширения браузера могут изменять файлы cookie и вызывать ошибки. Итак, в вашем браузере повреждена версия кеша. Попробуйте очистить файлы cookie и кеш вашего сайта. После очистки кеша страницы могут загружаться немного медленнее, потому что вашему браузеру потребуется перестроить кеш с часто используемыми данными. Но это могло помочь решить проблему.
Помните, что при очистке файлов cookie вам может потребоваться повторно ввести данные для входа на все веб-сайты. Вам нужны разные процедуры для очистки кеша и файлов cookie для каждого веб-браузера. Как правило, нажатие «Command + Shift + Delete» на Mac и «Control + Shift + Delete» в Windows работает в браузерах Chrome и Firefox.
4 Очистить DNS
На вашем компьютере могут быть устаревшие записи DNS, и это может вызвать ошибки. Вы можете очистить DNS и проверить, решает ли это проблему с ошибкой 400 HTTP. Это легко сделать, и это не вызовет нежелательных проблем.
5 Проверьте размер файла при загрузке
Ошибка HTTP 400 Bad или Invalid Request может произойти при попытке загрузить большой файл. Сначала проверьте разрешенный размер файла для загрузки. Если ваш файл больше, вы можете разделить его с помощью утилиты разделения файлов и загружать части файла по отдельности.
6 Проверьте другие веб-сайты
Если вы продолжаете получать ошибку HTTP 400 Bad или Invalid Request при попытке открыть веб-страницу, вам следует проверить, происходит ли это также с другими веб-сайтами. Если ошибка появляется снова, возможно, проблема с сетевыми устройствами на вашем компьютере. На компьютере под управлением Windows запустите программу диагностики сети, чтобы устранить проблему с подключением. На Mac может потребоваться отключить и снова подключить устройство.
Вы также можете обратиться к поставщику услуг Интернета, чтобы узнать, могут ли они решить проблему.
7 Перезагрузите свои устройства
Б. Для разработчиков
Если вы разработчик, вы можете получить ошибку 400 HTTP при тестировании собственного приложения. Следуйте приведенным ниже параметрам, чтобы исправить ошибку.
8 Исправить неверные заголовки HTTP
Иногда проверка деталей HTTP-заголовка может дать подсказку об ошибке подключения. Вы можете просмотреть детали HTTP-заголовка с помощью одного из бесплатных инструментов в Интернете. Хотя это легко сделать для разработчиков, для не-разработчиков это может быть довольно сложно.
9 Проверка журналов сервера
Веб-серверы обычно ведут журналы на стороне сервера для каждого запроса, отправляемого клиентом. Журнал может содержать такую информацию, как подключенное приложение, запрошенные страницы, IP-адрес и другую соответствующую информацию о запросах. Журналы сервера часто определяют причину сбоя и указывают статус обработки. Изучая журналы сервера, разработчики и администраторы могут легко определить причину проблем HTTP.
Если у вас нет доступа к файлам журнала сервера, запросите доступ у вашего хостинг-провайдера.
10 сценариев отладки или код приложения
Если вы получаете сообщение об ошибке в пользовательских приложениях, это может быть связано с плохо написанным кодом в приложении. Разработчикам необходимо вручную отлаживать приложение и проверять журналы сервера для выявления потенциальных проблем.
Наличие хорошей системы управления ошибками может эффективно помочь разработчикам устранить ошибку HTTP 400 Bad или Invalid Request. Даже если ошибки случаются, вы можете обнаружить их автоматически. Например, Airbrake – хорошая система мониторинга ошибок, предлагающая обновления в режиме реального времени. У него отличная панель инструментов, которая предлагает круглосуточные обновления о состоянии вашего веб-приложения. С помощью настраиваемого фильтра ошибок вы можете получать обновления о наиболее важных ошибках.
Заключение
Как объяснялось выше, ошибка 400 происходит из-за отправки неверного запроса на сервер. Это может быть связано с загрузкой файла или повреждением файлов cookie браузера. Следуйте приведенным выше решениям, и мы надеемся, что одно из них поможет вам решить проблему. Если проблема не исчезнет, это также может быть связано с дополнительными сторонними факторами между вашим браузером и сервером. Подождите некоторое время и попробуйте позже получить доступ к веб-страницам.
В пользовательских приложениях разработчики могут выполнять пошаговую отладку, чтобы найти реальную проблему.
Status Code 400
An HTTP (Hypertext Transfer Protocol Bad) State code 400 represents a user error. Whenever any user sends an invalid request to the server, the server immediately reports it and generates an HTTP based 400 bad request error. This error usually occurs if the user has entered an incorrect URL.
In the broad majority of likely situations, the status code 400 error occurs due to a client-side problem caused by the submitted request to the server or local caching causes. Hence, in this tutorial, we will cover various easy methods that anyone can implement even if the user is not tech-savvy. Following the given methods, you should be successfully able to make your website working!
What is a 400 bad Request error?
Status Code 400 or 400 Bad Request, or 400 error or HTTP error 400, is recognized by the server as a general user error. The server throws the 400 bad error if the server decides that the resulting error doesn’t come under any other status code classifications.
The 400 status code (Bad Request) represents that the server cannot process the request due to some user error. In return for an invalid request, the server should dispense the specific 4xx status code in the case of a failed request.
Common Causes of 400 error
A 400 Bad Request error is mostly the consequence of typing the incorrect URL in the browser window or making errors in an address link while linking it from a web page to another.
1. URL String Syntax Error
The primary reason for the HTTP error 400 to occur is an incorrectly typed URL (Uniform Resource Locator), deformed syntax, or a URL that contains some illegal characters.
Though the user can mistakenly type the wrong URL, it can sometimes happen if the URL encoding has been performed incorrectly. The below-given link is an example of an incorrect URL that the server won’t process, and therefore, it will trigger a 400 HTTP error.
2. Corrupted Browser Cache & Cookies
URL typo error is not the only case where the server triggers the 400 bad error. Even if the passed URL is 100% accurate, the server can still throw a 400 Bad Request error because it detects the presence of any corrupted files in the browser cache memory or other issues such as expired or damaged cookies.
The user can also encounter a 400 Bad Request error if he/she tries to gain access to their WordPress admin area after some time of their last log-in session. The reason why it occurred because the process following which the cookie was managing the login authentication information may have gotten expired, and it cannot further authenticate the same valid user with admin rights. And it eventually results in the connection being declined and therefore passes 400 Bad Request error.
3. DNS Lookup Cache
The 400 Bad Request can occur if the local DNS data stored is not in sync with registered DNS (Domain Name server) data. All the domain names available on the internet are the art of IP address. You can compare the IP address of your phone number as it connects to a particular «calling number» you wish to dial.
4. File Size Too Large
A 400 Bad Request can also trigger if the files uploaded by the user on a website are too heavy for the upload request to be met. This is strictly associated with the server’s file size limit and will change based on its setup.
5. Generic Server Error
The 400 bad request error can also occur if there is any technical issue on the server-side. Though, a 400 status code will display a generic problem with the server, server or network glitch, or any other undefined volatile issues.
Suppose it triggers when the user tries to connect to a third-party website, in that the user cannot control it. At that time, he/she can try to refresh the browser and monitor at frequent intervals whether the website developers have resolved the issue or not. Just in case you want to confirm whether the specific error is a server-side issue or not, try to load the website on various browsers, or you can also test it on a different machine/device to eliminate the system-specific problems.
If the same issue occurs with other browsers, systems are also confirmed to be a server-side problem. If the site content is important for you, you directly communicate to the website owner and give all the details related to Operating System, browser, system, and versions you were using when you experienced the 400 bad error issue.
How to fix 400 Errors
The various ways to fix the bad 400 errors are explained below:
1. Check the Submitted URL
One of the most common reasons for the 400 Bad Request error is the obvious URL string itself. One can easily make mistakes by manually typing unwanted characters in the URL in the web browser.
Re-check the spelling of the domain name or the particular web page you want to access and make sure that they are typed accurately and are separated with forwarding slashes. If the URL includes any special characters, make sure they are encoded properly with valid URL characters.
If you find it hard to check the URL spelling and encoding process repeatedly, you can opt for the online URL encoder/decoder. It is very useful for long URLs and less error-prone. These kinds of software help the user to identify various illegal characters in the URL automatically.
Once you have entered the correct URL, it’s time to run it again in the browser. Still, if you face the 400 Bad Request error, try with other fixing methods given below.
2. Clear Browser Cache
While accessing specific website content, the user receives a 400 Bad Request error if any website files stored locally have been corrupted.
It consists of all sorts of files that a website demands for its proper functioning, unlike:
Whenever any user visits any website, all the above files are stored locally on your computer’s browser. Therefore to fix this problem, one should clear the browser’s cache memory. Follow the below-given steps to clear the computer cache:
Note: Google provides you the option to delete only the recent files for a particular time range with the help of the Time range dropdown. However, to ensure all possibly corrupted files are eliminated, we suggest removing all stored files locally by selecting the All-time option.
3. Clear Browser Cookies
If you are still facing the 400 error even after clearing your browser cache, in that case, your browser cookies are also corrupted. Whenever you open any website on your browser, it uses different cookies. If any one of the used cookies gets expired or corrupted, then it can trigger the 400 Bad Request error.
To clear your cookies in web browser (Chrome in our case) follow the below given steps:
4. File Upload Exceeds Server Limit
While uploading a file, we often forget about the server size limit and exceed its maximum limit. Eventually, you confront a 400 Bad Request error.
Try to upload a file again, and this time upload a smaller file. If it gets uploaded successfully, then the likely error occurred because the initial file was too large, and before uploading the file again, either you need to trim the file size or need to find some way.
5. Clear DNS Cache
The 400 Bad request can be triggered if the DNS data stored locally gets corrupted or out-of-date.
Note: The local DNS data are not stored by the browser but on the OS (operating system).
6. eactivate Browser Extensions
Today, we install various extensions to our browser. Some extensions might affect your website cookies which could trigger the 400 bad request error. To find out the real culprit, temporarily disable them and check whether it makes a difference by running the website again.
Request failed with status code 400
This forum is closed. Thank you for your contributions.
Answered by:
Question
Here is the background. I deployed a LightSwitch 2013 web applicaiton to my local webserver using the publishing tool in Visual Studio. The site works great with no problems. I am able to load records from the external SQL Server. However when I deploy the exact same published package to our UAT web server I am having an issue. THere is an error statement where the data records are displayed that reads «Request failed with status code ‘400’ and status text ‘Bad Request’.» I turned on the Failed Request tracing for the application and found 2 logs. Here are the tracing logs:
The second log is identical to this log with the exception of the service being used.
I compared the IIS configs on the UAT server and my Dev server. The only differences that I could find are some missing assemblies on the UAT server. But I don’t really think this is the issue. The missing assemblies are these 3:
Microsoft.VisualStudio.Web.PageInspector.Loader, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
The application pools have identical configurations.
One other thing. I created a very basic Lightswitch application to display some database records to test the database connection. I deployed this to the UAT webserver and this application works perfectly. This app uses the same database as my real app.
Any help would be really appreciated. I am at a loss as to what the problem is. Thanks!
HTTP API Errors
We want your feedback
Common HTTP error codes used in the commercetools Composable Commerce APIs and the meaning of the error codes.
For details about the structure and application-specific error-codes of a specific commercetools Composable Commerce API, consult the documentation dedicated to that API.
Common HTTP error codes
400 Bad Request
A 400 is the most commonly expected error response and indicates that a request failed due to providing bad input. Bad input can be a malformed request body, missing required parameters, wrongly typed or malformed parameters or a parameter that references another resource that does not exist. Clients need to resolve the problems mentioned in the response before re-sending the request.
401 Unauthorized
A 401 indicates that the request is not properly authenticated.
403 Forbidden
A 403 indicates that the authenticated client is not allowed to perform the request.
404 Not Found
A 404 indicates that the addressed resource was not found / does not exist.
409 Conflict
A 409 indicates that the current version of the resource targeted by the request (with the intention to modify or delete it) is different from that provided in the request. In response to this, the client will usually want to request the newest version of the resource to see what has been changed and decide what changes to apply to the newest version.
A 409 Conflict indicates a concurrent modification and usually occurs on a versioned resource, which requires the client to provide the version of the resource to perform a change.
Whenever possible the HTTP response body contains the currentVersion field (optional) like this:
500 Internal Server Error
A 500 indicates that a request failed due to a server-side problem that needs to be resolved before subsequent requests can succeed. It either indicates a temporary unavailability or permanent server-side problem that needs to be reported and resolved.
502 Bad Gateway
A 502 indicates that a request failed due to a server-side problem caused by scaling infrastructure resources. The client application should retry the request with exponential backoff up to a point where further delay is unacceptable.
Error responses
The general structure of error responses from the API is as follows:
The error response always has the following fields:
Some errors have additional fields beside code and message and are documented appropriately.
The following sections describe the possible errors in the following way:
OAuth related errors
Errors related to authentication and authorization also conform to the OAuth 2.0 specification
Also note that error codes defined by the OAuth spec are not written in camelCase.
Errors from an API Extension
API Extensions can validate API calls and reject updates resulting in a 400 Bad Request response. API Extensions also have Error Cases.
When an API Extension is involved in the error, the errorByExtension field is added to the error response. The errorByExtension field contains the id and (if set) the key of the API extension. If the API Extension returns localizedMessage or the extensionExtraInfo fields in a Validation Error, they are also added to the error response.
General
500 Internal Server Error
The following general error codes can appear in responses with the HTTP status code 500 :
503 Service Unavailable
The following general error codes can appear in responses with the HTTP status code 503 :
OverCapacity
The service is having trouble handling the load.
The client application should retry the request with exponential backoff up to a point where further delay is unacceptable.
PendingOperation
A previous conflicting operation is still pending and needs to finish before the request can succeed.
The client application should retry the request with exponential backoff up to a point where further delay is unacceptable.
If these errors persist, they should be reported on the Support Portal
404 Not Found
The following general error codes can appear in responses with the HTTP status code 404 :
400 Bad Request
The following general error codes can appear in responses with the HTTP status code 400 :
AnonymousIdAlreadyInUse
The anonymous ID is already in use by another resource.
The client application should choose another anonymous ID or retreive an automatically generated one.
DuplicateField
A value for a field conflicts with an existing duplicate value.
Extra fields:
DuplicateFieldWithConflictingResource
A value for a field conflicts with an existing duplicate value stored in a particular resource.
Extra fields:
FeatureRemoved
The resource requested was removed.
The client application should use the feature recommended by the error message instead.
InvalidInput
Invalid input has been sent to the service.
The client application should validate the input according to the constraints described in the error message before sending the request.
InvalidJsonInput
Invalid JSON input has been sent to the service. Either the JSON is syntactically not correct, or the JSON does not conform to the expected shape (for example is missing a required field).
The client application should validate the input according to the constraints described in the error message before sending the request.
InvalidOperation
The resources involved in the request are not in a valid state for the operation. The client application should validate the constraints described in the error message before sending the request.
InvalidField
A field has an invalid value.
Extra fields:
InternalConstraintViolated
The discount code specified was never applied and cannot be updated.
MaxResourceLimitExceeded
No more resources of the type in this request can be created. Limits configuration should be adjusted for this resource before sending the request again.
Extra fields:
ObjectNotFound
The requested resource was not found.
ReferenceExists
A resource cannot be deleted because it is referenced by something else.
ReferencedResourceNotFound
A resource referenced by a Reference or a ResourceIdentifier could not be found.
Extra fields:
RequiredField
A required field is missing a value.
Extra fields:
ResourceSizeLimitExceeded
The resource exceeds the maximum allowed size of 16 MB.
SemanticError
The predicate is not semantically correct.
SyntaxError
The search query or predicate does not have correct syntax.
QueryTimedOut
The query timed out. If your query constantly times out, please check that it follows the performance best practices.
409 Conflict
The following general error codes can appear in responses with the HTTP status code 409 :
Extension error responses
The following error codes are returned when an API Extension triggered during an API request did not respond successfully.
400 Extension Predicate Evaluation Failed
502 Extension Bad Response
502 Extension Update Actions Failed
504 Extension No Response
External OAuth error responses
The following error code is returned when an External OAuth Introspection endpoint triggered during an API request did not respond successfully.
502 or 504 External OAuth Failed
Products
400 Bad Request
The following product-specific error codes can appear in responses with the HTTP status code 400 :
DuplicatePriceScope
A given price scope conflicts with an existing one. Every price of a product variant must have a distinct combination of currency, country, customer group, channel, valid from and valid until. These six properties constitute the scope of a price.
Extra fields:
DuplicateVariantValues
A given combination of variant values conflicts with an existing one. Every product variant must have a distinct combination of SKU, prices, and custom attribute values.
Extra fields:
DuplicateAttributeValue
The Unique AttributeConstraint was violated.
Extra fields:
DuplicateAttributeValues
The CombinationUnique AttributeConstraint was violated.
Extra fields:
Product Types
400 Bad Request
The following product type-specific error codes can appear in responses with the HTTP status code 400 :
AttributeDefinitionAlreadyExists
A given AttributeDefinition name conflicts with an already defined attribute.
Extra fields:
AttributeDefinitionTypeConflict
A given AttributeDefinition name already exists on another product type with a different type.
Extra fields:
DuplicateEnumValues
A given enum or lenum contains duplicate keys.
Extra field:
EnumKeyAlreadyExists
A given enum or lenum contains key that already exists.
Extra fields:
EnumKeyDoesNotExist
The enum or lenum already contains a value with the given key.
Extra fields:
AttributeNameDoesNotExist
An AttributeDefinition for the given attribute name does not exist.
Extra fields:
EnumValuesMustMatch
When reordering enum or lenum values all existent values must be passed
EnumValueIsUsed
When removing an EnumValue from a required attribute, but the EnumValue is still used by a product.
Orders
400 Bad Request
The following order-specific error codes can appear in responses to Create Order from Cart requests with the HTTP status code 400 :
OutOfStock
Some of the ordered line items are out of stock at the time of placing the order.
Extra fields:
PriceChanged
The price, tax, or shipping of some line items changed since the items were added to the cart.
Extra fields:
InvalidItemShippingDetails
A line item or custom line item has one or more shipping addresses set, but the quantity of that item does not match the sum of the quantities in its shipping details.
Extra fields:
MatchingPriceNotFound
The product variant does not have a price according to the Product’s priceMode value for a selected currency and/or country, customer group or channel.
Extra fields:
Error: Request failed with status code 400 when expo buidl
When you build expo you can face an error: at createError (/usr/local/lib/node_modules/turtle-cli/node_modules/axios/lib/core/createError.js:16:15) at settle (/usr/local/lib/node_modules/turtle-cli/node_modules/axios/lib/core/settle.js:17:12) at IncomingMessage.handleStreamEnd (/usr/local/lib/node_modules/turtle-cli/node_modules/axios/lib/adapters/http.js:260:11) at IncomingMessage.emit (events.js:322:22) at IncomingMessage.EventEmitter.emit (domain.js:482:12) at endReadableNT (_stream_readable.js:1187:12) at processTicksAndRejections (internal/process/task_queues.js:84:21) <
1 Answer 1
It seems that project is not published to Expo website.
You have to publish project first 🙂
Not the answer you’re looking for? Browse other questions tagged build expo or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Error: Request failed with status code 400 [expo-cli]
TL; DR
Logout from expo-cli and log in again
Intro
Yesterday I had an issue with expo-cli. I was testing some stuff on my phone and everything was great. I have used expo start to preview. After a few moments I kept expo-cli running and put my computer to sleep. A few hours later I’ve tried to preview the project following the same steps, which threw the error shown here
The issue seemed to be caused by axios. I have tried everything. I mean everything.
Removed all api calls, no help.
Reinstall expo, no help.
Reinstall expo-cli, no help.
I have almost started pulling my hair and then out of thin air I have come up with this idea which is explained down below.
I am not sure but I think this error was caused because I have left the expo-cli open.
I won’t dive deep into the details here because I am mostly certain that this error is because of expo-cli itself.
Well, I have found some solutions for the issue but non of them worked for me.
Here’s how I solved the issue
Solution
Just log out from expo-cli and log in again. That’s just it
More detailed approach of the solution
After start expo with expo start in the terminal you see an output like this
From here you need to hit s to log out.
Then you can hit s to log in again.
Now you won’t get the same error.
That was the solution for me. If you have any better ideas or solutions, feel free to write down below.
HTTP 400 (bad request) for logical error, not malformed request syntax
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
There seems to be a general practice among a few HTTP-based APIs these days to use 400 to mean a logical rather than a syntax error with a request. My guess is that APIs are doing this to distinguish between 400 (client-induced) and 500 (server-induced). Is it acceptable or incorrect to use 400 to indicate non-syntactic errors? If it is acceptable, is there an annotated reference on RFC 2616 that provides more insight into the intended use of 400?
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
As of this time, the latest draft of the HTTPbis specification, which is intended to replace and make RFC 2616 obsolete, states:
The 400 (Bad Request) status code indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
This definition, while of course still subject to change, ratifies the widely used practice of responding to logical errors with a 400.
HTTPbis will address the phrasing of 400 Bad Request so that it covers logical errors as well. So 400 will incorporate 422.
From https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p2-semantics-18#section-7.4.1
«The server cannot or will not process the request, due to a client error (e.g., malformed syntax)»
Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.
It could be argued that having incorrect data in your request is a syntax error, even if your actual request at the HTTP level (request line, headers etc) is syntactically valid.
I don’t know of any official references to back this up though, as usual it seems to be down to interpreting RFC 2616.
Update: Note the revised wording in RFC 7231 §6.5.1:
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).
seems to support this argument more than the now obsoleted RFC 2616 §10.4.1 which said just:
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
In English syntax rules prescribe certain relationships between parts of speech. For instance «Bob marries Mary» is syntactically correct, because it follows the pattern
The syntax of a simple URLis < protocol + : + // + server + : + port >. According to this «http://www.google.com:80» is syntactically correct.
But what about «abc://www.google.com:80»? It seems to follow the exact same pattern. But really it is a syntax error. Why? Because ‘abc’ is not a DEFINED protocol.
The point is that determining whether or not we have a 400 situation requires more than parsing the characters and spaces and delimiters. It must also recognize what are the valid «parts of speech».
This is difficult.
I think we should;
Return 4xx errors only when the client has the power to make a change to the request, headers or body, that will result in the request succeeding with the same intent.
Return error range codes when the expected mutation has not occured, i.e. a DELETE didn’t happen or a PUT didn’t change anything. However, a POST is more interesting because the spec says it should be used to either create resources at a new location, or just process a payload.
Using the example in Vish’s answer, if the request intends to add employee Priya to a department Marketing but Priya wasn’t found or her account is archived, then this is an application error.
The request worked fine, it got to your application rules, the client did everything properly, the ETags matched etc. etc.
Because we’re using HTTP we must respond based on the effect of the request on the state of the resource. And that depends on your API design.
Perhaps you designed this.
Returning a success code would indicate that the «replacement» of the resource worked; a GET on the resource would reflect your changes, but it wouldn’t.
So now you have to choose a suitable negative HTTP code, and that’s the tricky part, since the codes are strongly intended for the HTTP protocol, not your application.
When I read the official HTTP codes, these two look suitable.
The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict.
The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
Though we’ve traditionally considered the 500 to be like an unhandled exception :-/
I don’t think its unreasonable to invent your own status code so long as its consistently applied and designed.
This design is easier to deal with.
Then you could design your API to always succeed in creating the instruction, it returns 201 Created and a Location header and any problems with the instruction are held within that new resource.
A POST is more like that last PUT to a new location. A POST allows for any kind of server processing of a message, which opens up designs that say something like «The action successfully failed.»
Probably you already wrote an API that does this, a website. You POST the payment form and it was successfully rejected because the credit card number was wrong.
With a POST, whether you return 200 or 201 along with your rejection message depends on whether a new resource was created and is available to GET at another location, or not.
With that all said, I’d be inclined to design APIs that need fewer PUTs, perhaps just updating data fields, and actions and stuff that invokes rules and processing or just have a higher chance of expected failures, can be designed to POST an instruction form.
Как исправить ошибку 400 – подробная инструкция по решению проблемы
В наше время тяжело представить себе человека, который не пользуется услугами интернета. Кто-то черпает на его просторах необходимую информацию, кто-то наслаждается любимыми играми, а кто-то и вовсе — занимается удаленной работой.
Каждый из них, хоть раз, но сталкивался с тем, что на запрос определенной интернет страницы появлялось непонятное сообщение — «400 — Bad Request».
Что означает данное сообщение и почему возникает — обычный пользователь об этом не имеет не малейшего представления.
В нашей статье мы постараемся разобраться — что представляет собой 400 bad request как исправить и как в дальнейшем избежать возникновения подобной ситуации.
В компьютерном мире ошибка 400 (неверный запрос) возникает в том случае, если сервер не в состоянии обработать клиентский запрос. Подобное происходит вследствие неправильного синтаксиса, который способствует созданию необходимых взаимоотношений между различными веб-сервисами, а также клиентом и веб-приложениями.
Из-за этого довольно тяжело разобраться с причиной появления данной проблемы даже в контролируемой среде разработки.
На чьей стороне возникла ошибка
Для тех, кто еще не знает — если код имеет категорию 4хх — это данные ответа http, а ошибки с такими цифровыми значениями возникают на стороне клиента.
Под клиентом следует понимать как браузер, так и устройство, с помощью которого осуществляется доступ к приложению.
По своей сути, возникновение подобной ошибки может означать, что клиентское устройство отправило по какой-либо причине неверный запрос. Это может быть не только неправильно сформированный запрос, но и попытка провести загрузку слишком большого файла. Сюда же вполне можно отнести и неправильно сформированные заголовки http, которые также вызывают ошибку с кодом 4хх.
Рис.2 Сервер не смог распознать запрос.
Далее мы постараемся детально рассмотреть наиболее распространенные сценарии возникновения ошибки, а также возможные варианты ее решения.
Помните, что в данном случае объектом, генерирующим ошибку 400-Bad Request, может быть как клиент, так и запрашиваемый сервер.
Диагностирование ошибки
Возникновение ошибки неверного запроса может быть вызвано одной из ниже перечисленных причин:
Решение проблемы с клиентской стороной
Как бы то ни было, а наиболее правильным решением буде поиск и исправление неисправности клиентских устройств и приложений.
Первым делом стоит проверить правильность запрашиваемого URL.
Зачастую ошибка кроется в его некорректном вводе.
Рис.3 Пример отображения доменного имени и URL запрашиваемого сайта.
Не забывайте, что доменные имена — как бы вы их не набрали — ни в коей мере не повлияют на правильную работу ссылки.
К примеру, internet-company winter group.ru и inTErnet-COmpany grouP.ru будут работать абсолютно одинаково. Зато все, что касается URL — информация, идущая после доменного имени — чувствительны к регистру и должны иметь верное написание. В случае, когда URL содержит неправильные символы — сервер отвечает на запрос отображением кода возникшей ошибки.
Очистка файлов cookie
Наличие на локальном сервере идентичных или некорректных куки-файлов также является причиной появления ошибки 400 Bad Request.
Эти файлы представляют собой небольшое количество данных, которыми пользуются различные сайты для того, чтобы запомнить конкретное устройство или браузер, с которого осуществлялся запрос.
Благодаря этому все последующие визиты на такой сайт происходят намного быстрее, чем в первый раз.
Наличие таких куки-файлов создает удобство для пользователя, но может быть и причиной конфликта с токеном сессии другого пользователя. В данном случае одному из вас, а быть может и обоим одновременно, сервер выдаст ошибку 4хх.
Рис.4 Окно удаление файлов cookie.
При удалении cookie не следует полностью избавляться от всех имеющихся — достаточно удалить те из них, которые соответствуют определенному доменному имени.
Однако, если вы не имеете представление в выборочном удалении — будет наиболее правильным полностью очистить браузер от файлов cookie.
Каждый браузер располагает своей схемой очистки, однако, все они в чем-то схожи между собой.
Очистка кэш памяти браузера Chrome
После этих действий все сохраненные куки будут удалены из вашего браузера.
Загрузка файлов с меньшим объемом
Если вы загружаете определенный файл и получаете ошибку неверного запроса — возможно причина ее возникновения кроется в слишком большом объеме.
Попробуйте загрузить файл меньшего размера, чтобы удостовериться в корректной работе приложения.
Откат последних изменений
Если перед появлением ошибки 400 Bad Request вы делали обновление системы управления клиентом — решением проблемы может быть откат к ранее установленной версии.
Кроме этого, можно осуществить откат и обновленных расширений и модулей, так как они тоже могут являться причиной появления неприятной ситуации.
Удаление новых расширений и модулей
Некоторые расширения имеют неприятную особенность — изменять в базе данных таблицы и записи, которые им не принадлежат.
В этом случае придется удалить последние установленные расширения, а затем вручную очистить базу данных от их последствий.
Переустановка программы Windows Operating System
Неправильная работа данной программы может послужить причиной возникновения Bad Request. Для решения вопроса следует произвести ее переустановку.
Рассмотрим удаление данной программы на примере ОС Windows 7.
Для этого выполните следующие действия:
Рис.5 Окно «Программы и компоненты».
После удаления вам понадобится заново установить эту программу, воспользовавшись инструкцией Microsoft Corporation.
Выявление и удаление вредоносов
Еще одной причиной, способной вызвать ошибку 400, является заражение вашего компьютера различными вредоносными программами.
Такие программы могут изменить либо полностью удалить файлы состояния браузера.
Кроме того, некоторые компоненты вредоносной программы могут сами служить причиной возникновения ошибки.
Чтобы иметь возможность защиты от подобного рода программ — установите на компьютер соответствующее приложение. Одним из лучших является Emsisoft Anti-Malware. Это приложение не только защищает, но и гарантированно удаляет любое вредоносное ПО.
Рис.6 Программа Emsisoft Anti-Malware.
Обновление драйверов
Как ни странно, но устаревшие или некорректно работающие драйвера тоже способны создать подобную проблему, поэтому старайтесь как можно чаще проверять их работоспособность и вовремя проводить обновление.
Вручную проверять и обновлять каждый драйвер слишком долго, поэтому проще всего установить на компьютер такую программу, как DriverDoc, которая полностью избавит вас от этой рутинной работы.
Обновление Windows
Корпорация Microsoft не прекращает работу, связанную с обновлением и улучшением системных файлов своих операционных систем.
В некоторых случаях необходимо просто обновить коды состояний браузера и ошибка Bad Request исчезнет сама собой.
Рис.7 Окно обновления Windows.
Для этого понадобится воспользоваться кнопкой «Начать» и ввести в строку поискового запроса «update» (обновление), после чего нажать на клавишу Enter.
В этом случае откроется диалоговое окно обновления ОС, в котором будут отображаться все доступные пакеты (если такие имеются).
Если ни один из вариантов не помог избавиться от возникшей проблемы — обратитесь к специалистам.
Видеоролик на тему решения проблемы 400 Bad Request:
A Complete Guide and List of HTTP Status Codes
HTTP status codes are like short notes from a server that get tacked onto a web page. They’re not actually part of the site’s content. Instead, they’re messages from the server letting you know how things went when it received the request to view a certain page.
These kinds of messages are returned every time your browser interacts with a server, even if you don’t see them. If you’re a website owner or developer, understanding HTTP status codes is critical. When they do show up, HTTP status codes are an invaluable tool for diagnosing and fixing website configuration errors.
This article introduces several server status and error codes, and explains what they reveal about what’s happening on the server behind the scenes.
Prefer to watch the video version?
What Are HTTP Status Codes?
Every time you click on a link or type in a URL and press Enter, your browser sends a request to the webserver for the site you’re trying to access. The server receives and processes the request, and then sends back the relevant resources along with an HTTP header.
HTTP status codes are delivered to your browser in the HTTP header. While status codes are returned every single time your browser requests a web page or resource, most of the time you don’t see them.
It’s usually only when something goes wrong that you might see one displayed in your browser. This is the server’s way of saying: “Something isn’t right. Here’s a code that explains what went wrong.”
Google 404 HTTP status code
If you want to see the status codes that your browser doesn’t normally show you, there are many different tools that make it easy. Browser extensions are available for developer-friendly platforms such as Chrome and Firefox, and there are many web-based header fetching tools like Web Sniffer.
To see HTTP status codes with one of these tools, look for the line appearing near the top of the report that says “Status: HTTP/1.1”. This will be followed by the status code that was returned by the server.
Understanding HTTP Status Code Classes
HTTP status codes are divided into 5 “classes”. These are groupings of responses that have similar or related meanings. Knowing what they are can help you quickly determine the general substance of a status code before you go about looking up its specific meaning.
The five classes include:
Within each of these classes, a variety of server codes exist and may be returned by the server. Each individual code has a specific and unique meaning, which we’ll cover in the more comprehensive list below.
Why HTTP Status Codes and Errors Matter for Search Engine Optimization (SEO)
Search engine bots see HTTP status codes while they’re crawling your site. In some cases, these messages can influence if and how your pages get indexed, as well as how search engines perceive the health of your site.
Sign Up For the Newsletter
Want to know how we increased our traffic over 1000%?
Join 20,000+ others who get our weekly newsletter with insider WordPress tips!
Generally speaking, 100- and 200-level HTTP status codes won’t have much impact on your SEO. They signal that everything is working as it should on your site, and enable search engine bots to continue on their way. However, they aren’t going to boost your rankings either.
For the most part, it’s the higher-level codes that matter for SEO. 400- and 500-level responses can prevent bots from crawling and indexing your pages. Too many of these errors can also indicate that your site isn’t of high quality, possibly lowering your rankings.
300-level codes have a bit more complicated relationship with SEO. The main thing you need to know to understand their impact is the difference between permanent and temporary redirects, which we’ll cover in more detail in the relevant section below.
In a nutshell, however, permanent redirects share link equity from backlinks, but temporary ones do not. In other words, when you use temporary redirects for pages that have moved, you lose the SEO advantage of all the link building you’ve done.
Checking for HTTP Status Codes in Google Search Console
One way to monitor how Google perceives the HTTP status codes on your site is to use Google Search Console. You can view 300-, 400-, and 500-level status codes in the Coverage report:
Google Search Console’s Coverage report
This area of your dashboard shows four types of content on your site:
You may find pages with 300-, 400-, and 500-level HTTP status codes under the Excluded, Error, or Valid with warnings sections, depending on the type of code. For instance, 301 redirects may be listed under Excluded as Page with redirect:
A page with a redirect in Google Search Console’s Coverage report.
400- and 500-level status codes will likely turn up under Error.
Another way to view HTTP status codes is by using the URL Inspection tool. If Google is unable to index a specific page due to an error, you’ll see that here:
A 404 error in Google Search Console’s URL Inspection tool
For more tips on using Google Search Console, check out our comprehensive guide to the platform.
A Complete Guide and List of HTTP Status Codes
While there are over 40 different server status codes, you’ll likely encounter fewer than a dozen on a regular basis. Below, we’ve covered the more common ones, as well as a few of the more obscure codes you may still run across.
Stumped by an HTTP status code? Our WordPress experts are standing by. Try Kinsta for Free.
100 Status Codes
A 100-level status code tells you that the request you’ve made to the server is still in progress for some reason. This isn’t necessarily a problem, it’s just extra information to let you know what’s going on.
200 Status Codes
This is the best kind of HTTP status code to receive. A 200-level response means that everything is working exactly as it should.
300 Status Codes
Redirection is the process used to communicate that a resource has been moved to a new location. There are several HTTP status codes that accompany redirections, in order to provide visitors with information about where to find the content they’re looking for.
400 Status Codes
At the 400 level, HTTP status codes start to become problematic. These are error codes specifying that there’s a fault with your browser and/or request.
Stumped by an HTTP status code? Our WordPress experts are standing by. Try Kinsta for Free.
500 Status Codes
500-level status codes are also considered errors. However, they denote that the problem is on the server’s end. This can make them more difficult to resolve.
Where to Learn More About HTTP Status Codes
In addition to the HTTP status codes we’ve covered in this list, there are some more obscure ones you may want to learn about. There are several resources you can consult to read up on these rarer codes, including:
Knowing these status codes may help you resolve some unique issues while maintaining your own website, or even when you encounter them on other sites.
Summary
While they may seem confusing or intimidating on the surface, HTTP status codes are actually very informative. By learning some of the common ones, you can troubleshoot problems on your site more quickly.
In this post, we’ve defined 40+ HTTP status codes that you may encounter. From the milder 100- and 200-level codes to the trickier 400- and 500-level errors, making sense of these messages is crucial for maintaining your website and making sure it’s accessible to users.
Save time, costs and maximize site performance with:
All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.
What HTTP status response code should I use if the request is missing a required parameter?
I am thinking 412 (Precondition Failed) but there may be a better standard?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Status 422 seems most appropiate based on the spec.
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
They state that malformed xml is an example of bad syntax (calling for a 400). A malformed query string seems analogous to this, so 400 doesn’t seem appropriate for a well-formed query-string which is missing a param.
Note: Since the above RFC is about WebDAV there can be a misunderstanding that 422 and some others are only to be used in the context of WebDAV and using them outside of it is «nonstandard». But this only means these status codes were introduced in the context of this RFC. Indeed the wording of these definitions is carefully chosen not to be specific to WebDAV.
Why Does my HttpWebRequest Return 400 Bad request?
The following code fails with a 400 bad request exception. My network connection is good and I can go to the site but I cannot get this uri with HttpWebRequest.
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
First, cast the WebRequest to an HttpWebRequest like this:
Then, add this line of code:
Set UserAgent and Referer in your HttpWebRequest:
There could be many causes for this problem. Do you have any more details about the WebException?
One cause, which I’ve run into before, is that you have a bad user agent string. Some websites (google for instance) check that requests are coming from known user agents to prevent automated bots from hitting their pages.
In fact, you may want to check that the user agreement for YouTube does not preclude you from doing what you’re doing. If it does, then what you’re doing may be better accomplished by going through approved channels such as web services.
HTTP Status Codes For Invalid Data: 400 vs. 422
Let’s say that someone makes a request to your server with data that is in the correct format, but is simply not «good» data. So for example, imagine that someone posted a String value to an API endpoint that expected a String value; but, the value of the string contained data that was blacklisted (ex. preventing people from using «password» as their password). What HTTP status code would you return?
Until now, I would have returned a «400 Bad Request», which, according to the w3.org, means:
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
This description doesn’t quite fit the circumstance; but, if you go by the list of core HTTP status codes defined in the HTTP/1.1 protocol, it’s probably your best bet.
Recently, however, Jamie Krug pointed out [to me] that popular APIs are starting to use HTTP extensions to get more granular with their error reporting. Specifically, many APIs, like Twitter and Recurly, are using the status code «422 Unprocessable Entity» as defined in the HTTP extension for WebDAV. HTTP status code 422 states:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Going back to our password example from above, this 422 status code feels much more appropriate. The server understands what you’re trying to do; and it understands the data that you’re submitting; it simply won’t let that data be processed.
HTTP status code 422 feels like a much more appropriate response for situations where the data is understood, but is still not valid. I think I’ll start using this going forward. Thanks Jamie!
Enjoyed This Post? ❤️ Share the Love With Your Friends! ❤️
You Might Also Enjoy Some of My Other Posts
Reader Comments
Great catch. I’ll have to add that one to my list of things to watch out for in all of the remote services I’ve been working on lately.
My pleasure! When I first read a spec definition for 422, it still didn’t feel like a perfect fit, but it does seem better fit than 400. Cheers.
Yeah, still seems a bit odd. Like, what about if you go to create a NEW user, but provide a blacklisted email address? There is no «entity» yet to process. But, I guess it means you can’t create an entity to process. anyway, seems like an upgrade from 400.
. or maybe I am using the term «entity» in too narrow a view. Maybe they just mean «data entity», not «object entity.»
I agree, 400 shouldn’t be used here, as the http request is syntactically valid and conform to the protocol specifications.
If you write a custom client application or any other form of machine-machine interface, it may have a more distinct meaning (other than «something went wrong»), but nobody stops you from using 499 or any other custom 4xx code anyway.
By starting to rely on non-2xx responses for errors, it means that successful responses can simply return the «payload» and error handlers can take error messages. It’s been a long journey, but I have found that this is a bit more of an elegant and useful solution.
But, like I said, I was returning 200 for years and obviously, it worked, so I’m not saying it’s a bad move.
I stumbled across this a while back. Maybe from your site!
The (ColdFusion 9) code will dump a list of HTTP status codes.
Oh cool. It’s been a while since I’ve toyed around in the underlying page response object. Good stuff!
Nah, 400 is correct in this case. «Syntax» doesn’t just mean «well-formed XML» (or JSON or post data or whatever), it means that it’s syntactically correct in the context of the application.
This is not the case here.
As a POST body can contain arbitrary data, a problem with these data can only arise when the provided mime types does not match the body encoding (i.e. «application/x-www-form-urlencoded» when sending an XML or JSON body), or the encoding is invalid (bad XML structure, for instance).
These are all encoding (syntax) problems.
If there is no problem interpreting the body data, but a problem with the contents of these data (like Ben outline in the opening post), a 400 status code is not justified.
I don’t read the spec that way: if an XML request entity is not well-formed then respond 400 and say «couldn’t parse XML» in the response body, and if it has a «foo» element in place of a «bar» then respond 400 and say «found foo in place of bar» in the response. I understand the nuanced situation 422 is supposed to address, I just don’t think it’s necessary.
406 and 409 are completely wrong in this context.
If a problem arises from the payload (does not matter if syntactical or semantical), it is not a problem directly related to the http transport mechanism, and should not be indicated with http means.
This is a bit above my philosophical pay-grade, but perhaps the problem is that the HTTP spec was written before there was such a huge focus on 3rd-party APIs. As such, not very much was built into the spec to transport meta-data about the response?
Or maybe they [who designed HTTP] were just expecting all data to be returned inside a content body, like a SOAP envelope?
My biggest concern with wrapping error data inside a body transport is that the receiver-side of the API request needs to then be able to differentiate two different kinds of failures: HTTP failures (such as 400) and business-logic failures. And, if the latter is wrapped in a response with a 200OK status code, then the receiver needs to examine the OK responses more deeply to figure out if they were a success or a failure.
But again, I’m just a developer with zero experience in networking; so, I won’t be pretend to say any of the above with any confidence 🙂
but wasn’t that exactly my point to not mix up HTTP transport and business-logic?
Granted, it is convenient to report a problem in the http status code already (and save the hassle of parsing the http body), but.
That’s why there is no appropriate http status code for «something went wrong in the business logic layer», and frankly, if we start to add such http result codes, we will have a gazzillion new error codes in no time.
Just imagine this:
Your business logic only calls fetchData() with the URL and (optional body data), and returns an already parsed JSON object or an integer status code on error.
The fetchData() subroutine handles all the http stuff, i.e. redirections are resolved automatically and re-requested, and everything that cannot be handled results in an error report (and leaves it to the business logic to decide what to do, i.e. try a different server)
This way, the business logic doesn’t «ooze» into the networking stuff and vice versa.
Both can be tested independently (you can do as many fetchData() calls for testing as you like) and the business logic can be tested by making fetchData() return whatever you need to test.
And the best part is that you can re-use your thoroughly tested network logic in other projects, as it is completely independent from any business logic.
This is the way to create rock solid code, the only way imho.
«Weeks of coding can save you hours of planning.»
I’m sorry, forgot to answer your question in my last post, so here you go:
The hyper text transfer protocol (HTTP) was originally designed by Roy Fielding, Tim Berners-Lee and others at CERN. It is meanwhile maintained by the IETF, just as any other RFC.
I guess I would quibble with «http status codes. have no relation to what happens in the business-logic layer.»
E.g., imagine an application where a given resource can only be DELETEd by certain users (admins, the resource owner, or whatever) as identified in the Authorization header. The determination for who can DELETE what is completely in the realm of business logic, but if a different user makes the request then a 403 response seems completely appropriate according to the spec.
http only defines access in a yes/no way (basic, digest and nowadays oauth), so if you have access to a resource (read-only is enough), you can’t reply wih a 403 Forbidden.
If you add more granularity (read: yes, delete:no), it all happens in the business logic, and has to be reported as part of the business logic (in the http body data).
When it is not a http problem, why indicate a http problem?
Someone using your service/API will curse you for days when it is not clear why a resource that he was able to read just seconds ago is now «Forbidden» all of a sudden.
How is DELETE beyond the scope of HTTP? It’s in the spec!
sorry, didn’t realize that you were talking about the DELETE request method.
The DELETE command is in the http itself (header), not in the http payload (body), and when you issue a DELETE it will be clear what a 403 in return means.
That’s entirely different to what happens in the http payload and should stay separated.
Please have a look at how i.e. apache handles WebDAV access rights, it’s all done in the server configuration.
If you write your own server/client application, which nobody else will ever use, then, by all means, go for it and (ab)use whatever you like.
But if you write code like that for a public API, stick to what other people (read: fellow coders) know and expect (even if that’s not always 100% standard).
If i’d receive a 4xx error in return when calling your API, the last thing i’d consider is a problem within the body data.
Fair enough. By the same token, if I were to attempt to update a resource with a PUT request when calling *your* API, and got a 200 status in response, then the last thing I would expect is that the resource might not in fact have been updated.
Always interesting to hear other perspectives on stuff like this, though. Thanks!
Why would i respond to a PUT operation with a 200 when an error occurs?
That’s a plain vanilla http operation, hence the use of http status code is not only justified, it is mandatory.
(i.e. 201 Created or something like that)
There are, besides WebDAV, no applications using PUT or DELETE «in the wild», so this is a merely academical consideration. The specs list a lot of stuff that was meant to become part of HTTP/1.2 or even 2.0 (like 402 Payment Required).
Don’t do that, if you really hate parsing that much, how about adding a custom header field instead to indicate success/failure of the operation?
But you should return the error in the body nonetheless.
«Why would i respond to a PUT operation with a 200 when an error occurs?»
So what do you use then? A client tries to PUT a resource and you determine that for whatever reason it’s invalid in the context of your application and reject the request. The status code you use is.
Frankly, i wouldn’t use PUT at all, there are other means to upload a file (i.e. mimic the behaviour of a html FORM elements and send a multipart/form-data encoded body)
But, let’s say i would need it for a project (not trying to dodge your question here), i’d implement WebDAV (as far as i need it) and return a status code in compliance with the WebDAV specs.
This way i am using either RFC2616 (HTTP/1.1) or RFC2518 (WebDAV) and not some homegrown, incompatible modifications to standards.
If the error is a result of a http operation, report the error with an appropriate http status code.
If it’s WebDAV operation (DELETE, PUT. ) use the http status codes including those added for WebDAV.
If the error occurs in the business logic, report the error in the body and use 200 Ok
There are a few exceptions though, i.e. the business logic should be able to trigger a 500 response when something really goes foobar and replying with a proper response in the body is not possible.
Cool, I think we are just coming at things from totally different perspectives. If your API is limited to GETs and form data, then I can see that you wouldn’t be able to rely on status codes as much as is possible in a more RESTful design.
FWIW, PUT is very much part of HTTP/1.1 and in no way homegrown or limited to WebDAV (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6).
I know, i was the one coming up with the specs, but «commonly used like that» outweights the specs by far.
I have never seen any good use of PUT and DELETE outside of WebDAV, and not even WebDAV is much used.
(Microsofts fault mainly, but let’s better not go there)
«I have never seen any good use of PUT and DELETE outside of WebDAV, and not even WebDAV is much used. «
I mostly agree. For years, I used nothing but GET and POST and I was able to build very robust applications. I pretty much never use PUT. DELETE, I use.
own API, own client = do whatever you like.
A «488 Ben says: Invalid parameter type» would work fine, too, not sure why you make an effort to find an appropriate existing status code when you don’t stick to standards anyway. 😉
Every 4xx status code should work fine with any http(s) library out there.
However, i, for one, would still not do that (nor hire someone who does):
Imagine you win the lottery and move to Hawaii, and your customers are stuck with heavily customized code nobody can maintain/enhance.
Same goes for own projects, you might be too busy to code everything yourself one day and hire someone who runs into the same problem.
There is a sizable part of me which *wants* to follow standards; which I guess is why I’ve been trying hard to find an existing code that makes sense. But, I do all that in the context of not having a perfect grasp of the standard.
As far as efficiency goes, I’m not concerned about the data transfer. I agree that passing a small amount of JSON data would be negligibly different from passing an HTTP status code and text response. When I talk about «efficiency», I mean in the way the response is actually handled on the client-side.
Imagine that all the AJAX requests to the server are encapsulated behind a Promise object which allows for success/error bindings. If an error can cause both 4xx responses (HTTP error) and 2xx responses (application error), then there is an extra layer of checking in my client-side success handlers (pseudo code):
By shoe-horning application errors into «http errors,» then I can have a simpler separation between «success» and «fail» responses. That’s what I mean by efficiency.
you still shouldn’t «bend» the standards for that.
You have posted a tricky example, because request.done can’t call request.fail here directly, but if don’t use a lambda style function for fail here and instead pass a static function, you can.
It’s only a few more additional lines, plus, the static errorHandler function is way more efficient than creating a new lambda-style function every time you make an ajax request.
(Actually, deferred object are real resource hogs, as you create all the functions anew for every new promise object, but i digress. )
A few years ago, when Promises were first introduced to jQuery, I did play around with using the pipe() method and wrapper promises to actually shoe-horn structured responses into the a single error handler:
Without having to read those, the gist of the posts is that the server always returns a structured response with a 200 OK status. Then, on the client, the pseudo-code is as follows:
In those old posts, I actually DO return a 200 OK response for all «successful» HTTP requests, and then encapsulate the business-logic-failure within the structure response. Then, I use a response preprocessor to route the response to the error-handler IF the business logic indicates a failure.
I’ve never really thought of the Promise as being a resource hog. I mostly assume that as long as we don’t create circular references in the closures to DOM elements, then memory [leaks] is not too much of a concern.
In those old posts, I actually DO return a 200 OK response for all «successful» HTTP requests, and then encapsulate the business-logic-failure within the structure response. Then, I use a response preprocessor to route the response to the error-handler IF the business logic indicates a failure.
If you already did it this way before, i wonder why you don’t stick to that concept and try to dabble with http response codes now.
It feels a bit like you’re trying to evolve, to refine the way you do things, and take a step back without realizing it.
I’ve never really thought of the Promise as being a resource hog. I mostly assume that as long as we don’t create circular references in the closures to DOM elements, then memory [leaks] is not too much of a concern.
But i mentioned that only because you were so worried about efficiency, it’s not like it’a a big deal when the functions passed are somewhat small.
Definitely, I am always trying to evolve in my programming skills. And that probably is a two steps forward, one step back kind of thing.
I’ve never used AngularJS, and very likely never will.
And what i don’t really believe is that AngularJS kinda leaves you with no other (practicable) cchoice than abusing http status codes.
It seems we’ve taken a wrong turn somewhere, my example addressed your example, but that does not mean it is limited to Promise objects.
However, you already made a decision for the current project, so i can only hope that you remember my objections here when you start a new project.
It’s not just AngularJS: Backbone, Spine, and presumably pretty much every other frontend framework that’s around these days is geared towards talking to REST interfaces using the full assortment of methods and status codes defined in the HTTP spec.
That’s one reason it took me a minute to understand where you were coming from: eschewing PUT/DELETE and error statuses is a fairly eccentric approach, though of course you can make anything work.
every xmlhttprequest is «geared towards» the full set of request verbs/status codes.
If your particular frontend library is using well-documented (read:standardized) methods for other means, it is basically only mimicking http (and WebDAV).
SIP mimics http, too, but nobody would say that SIP is using http standards.
«If your REST implementation resorts to a wild mixture of http and WebDAV it is nonetheless a «homegrown» protocol and does not follow standards. «
Totally agree, that’s my original reason for not liking 422 in this case.
Our only difference is between «return 400 and an error description in the body» vs. «return 200 and an error description in the body.»
Responding «200 OK» to a request that failed is clearly contrary to the plain language of the HTTP spec.
but 400 is defined as follows (taken from RFC2616):
400 Bad Request
The request could not be understood by the server due to malformed syntax.
This applies to «malformed syntax» of the header only, because the standard does not define anything related to the body data.
The request per se succeded (you’ve sent back data, mind you!), the body actually contains valid data, so i opted for a 200.
My interpretation of RFC2616 is this (and that’s how i’ve implemented it in the past):
400 is merely a reply to a junk request, a port number that has been mistakenly used for a different protocol or out-of-sync (meaning the server tries to i.e. interprete parts of the body data as request), and what’s more important, the server should close the tcp connection directly after sending the response (header!), so the client won’t i.e. send an out-of-sync request over that tcp connection again.
According to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4 all 4xx responses should describe the error in the response body.
I know, but it doesn’t make sense to simply repeat ‘Bad Request’ in the http body.
All of the scenarios that i’ve listed above indicate that the client would not interprete the response correctly/at all anyway.
And it makes even less sense to do that when your body contains a JSON string, that is not really suited to be displayed to the end-user.
I.e. no browser displays the 401 Unauthorized to the user, they use a pop-up window for user credentials, so it’s not like this basic rule applies to every 4xx code in the same way.
But that’s only a side scenario.
You ignored my main point though, the «malformed syntax» part covers only the http header and not the body.
Right, you don’t repeat «Bad Request,» you spell out the reason it was rejected. E.g., «the specified ‘foo’ must be between 7 and 12.»
IMHO 5xx errors are the exclusive domain of the web server, and 4xx are fine to return from the application.
Interestingly, just noticed the spec calls out 404 as «commonly used» when no other error status applies: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5
But also note that the HTTPbis working group’s draft describes 400 a little more broadly than the HTTP/1.1 spec: http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#page-57
I don’t think we’re ever going to agree on this. But I maintain that returning what is explicitly defined as a «success» response to a request that was not fulfilled is, at the very least, surprising.
I see where you’re coming from, but yes, we’re very likely not going to agree on this. at least not anytime soon. 😛
I, for one, would be surprised to have a 400 response with body data in the expected format (instead of a placeholder, i.e. human readable text/html instead of the expected JSON data)
A 200 response clearly contains something i can parse without having to worry that the server sent some placeholder text.
The server won’t send a 200 on it’s own when addressing a script, and that’s one of my main reasons to prefer it over any other 4xx/5xx code!
Thanks for the suggestion, I’ve been wanting to come up with a standardized way to handle exceptions for a long time. I used the same thing you did, a flag at the top level of the response with a 200, but that felt really wrong. We’re going to use 422 (or if people really don’t like using a WebDav extension, we’ll fallback to 400). In that case, the body of the response is going to contain a list of errors with our application specific error code, maybe some exception specific data and a message to display to the user.
Most public APIs use 4xx to indicate a business logic error, YouTube, Amazon, Twitter etc, so whether or not this fits the rigid definition of the standard, I would much rather go with what these large and technically savvy companies use/
Anyway, by your definition of HTTP status codes, 403 does not make any sense. 403 clearly states that the request was completely valid but the server is refusing to respond to it, for instance due to business rules.
the http request IS completely valid, because http does neither define nor perform checks of the http payload (that’s solely a matter of the business logic).
And it’s the business logic that refuses to complete the requested action.
Whether others use this or not is not authoritative, but, if you insist on indicating a business logic problem in a http status code, (unnecessarily intertwining business and transport logic), why not use a 4xx status code that doesn’t have an accurately defined meaning yet?
2. The HTTP error codes are indeed targeted to be interpreted by Stacks (first) but 99% percent of the time they get propagated to the user simply dressed up differently so the separation of concerns you argue for is pretty much semantics.
What not ok is that you are prepared to introduce complexity in the form of custom entity formats, unnecessary confusion and incompatibility with standard logging/debugging tooling just to avoid a deviating a bit.
Furthermore, on a conceptual level, I see no problem in having HTTP return a generic Application Error code. HTTP does not live in vacuum and if you noticed most of its core operations are defined in terms of (application) business processes (posting to a bulletin board etc. )
Think proportional, the standards will eventually get tuned to align with what’s on the ground.
i really have a hard time to take feedback riddled with lols for serious.
Nonetheless i’ll try to reply:
Engineering trade off is just a different term for «diluting the standards» here.
Rape http as much as you like, add new request verbs, 8xx status codes, whatever you please (or need to get your stuff done) but don’t go telling everyone it is still http.
Let me, once again, rephrase it, because it still appears to be a problem:
Basically, you have two options.
a) stick to the standard
b) create your own protocol (based on http)
If you option a) is your choice, there is no need to discuss this any further, because http does not define a status code for «bad payload data».
Standards are important. Imagine 1,000,000 coders and everyone is adding at discretion. which means there IS NO STANDARD anymore.
And with the standard you lose compatibility and interoperability.
To sum it up:
Don’t mess with the standards.
If you need more than the standards lets you do, DERIVE.
Best practice is to stick to the payload with your custom needs entirely.
If you can’t see the value (in this particular context) and you truly believe that by using the WebDAV 422 Status Code Extension to HTTP/1.1 for distinguishing application level errors is «diluting the standards», «Rape http as much as you like» then please accept my apology for misinterpreting the discussion.
And why should anyone need a custom parser?? Are you being serious??
If everybody may change standards at will, there will be (insert arbitrarily big number) of different «flavours» of that standard in a wink and that means there is no standard anymore.
Applies to every standard there is.
Why do you have such a hard time to accept something that is so painfully obvious?
Please, ask yourself what the purpose of having standards in the first place might be. A surprising insight is right in the line for your there.
HTTP response status codes
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:
The below status codes are defined by section 10 of RFC 2616. You can find an updated specification in RFC 7231.
Note: If you receive a response that is not in this list, it is a non-standard response, possibly custom to the server’s software.
Information responses
This interim response indicates that the client should continue the request or ignore the response if the request is already finished.
This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.
This code indicates that the server has received and is processing the request, but no response is available yet.
This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.
Successful responses
The request succeeded. The result meaning of «success» depends on the HTTP method:
The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.
This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the 200 OK response is preferred to this status.
There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones.
Tells the user agent to reset the document which sent this request.
This response code is used when the Range header is sent from the client to request only part of a resource.
Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
Used inside a response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
Redirection messages
The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.)
The URL of the requested resource has been changed permanently. The new URL is given in the response.
This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
The server sent this response to direct the client to get the requested resource at another URI with a GET request.
This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.
The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
Client error responses
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).
Although the HTTP standard specifies «unauthorized», semantically this response means «unauthenticated». That is, the client must authenticate itself to get the requested response.
This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.
The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource.
This response is sent when the web server, after performing server-driven content negotiation, doesn’t find any content that conforms to the criteria given by the user agent.
This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
This response is sent when a request conflicts with the current state of the server.
This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for «limited-time, promotional services». APIs should not feel compelled to indicate resources that have been deleted with this status code.
Server rejected the request because the Content-Length header field is not defined and the server requires it.
The client has indicated preconditions in its headers which the server does not meet.
Request entity is larger than limits defined by server. The server might close the connection or return an Retry-After header field.
The URI requested by the client is longer than the server is willing to interpret.
The media format of the requested data is not supported by the server, so the server is rejecting the request.
The range specified by the Range header field in the request cannot be fulfilled. It’s possible that the range is outside the size of the target URI’s data.
This response code means the expectation indicated by the Expect request header field cannot be met by the server.
The server refuses the attempt to brew coffee with a teapot.
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
The request was well-formed but was unable to be followed due to semantic errors.
The resource that is being accessed is locked.
The request failed due to failure of a previous request.
Indicates that the server is unwilling to risk processing a request that might be replayed.
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).
The origin server requires the request to be conditional. This response is intended to prevent the ‘lost update’ problem, where a client GET s a resource’s state, modifies it and PUT s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
The user has sent too many requests in a given amount of time («rate limiting»).
The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.
The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
Server error responses
The server has encountered a situation it does not know how to handle.
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
This error response is given when the server is acting as a gateway and cannot get a response in time.
The HTTP version used in the request is not supported by the server.
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
The server detected an infinite loop while processing the request.
Further extensions to the request are required for the server to fulfill it.
Indicates that the client needs to authenticate to gain network access.
React js sending json to Spring boot Request failed with status code 400
I’m trying to send a state created in the front react js part to the backend spring boot part and read my state in JSON mode, I used Axios but I get this error:
Request failed with status code 400
my frontend code :
Controller in back end :
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Firstly, you can remove the @Controller annotation from your controller as you already have the @RestController annotation to make it a rest controller. Secondly, if yoou want to have a request body or json send to the endpoint use a POST request. If you ask me why not to use a Request body with a GET request, the short version is it’s because of HTTP spec, read : HTTP GET with request body
Create the POJO class FilterRegion with the fields in the json like :
I’m trying to access an API using Postman to get a response using basic authentication, but when I submit the data, it gives me the dreaded 400 error, which apparently indicates that some headers aren’t set up properly.
Here’s the API info:
And in response, I should get an encrypted token in form of JSON, instead I’m getting this error.
Here are the postman screenshots:
Am I missing something?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I also faced the same issue and i updated my postman header with the below image. And issue solved.
In the Body section of the request but your images don’t show that you’ve added that to the Body on any request, you’ve added it as a Auth header instead, so remove that before trying again. I’m not sure of the need to add the Content-Length header as that will change for different username and password combinations in the payload or for the length of the response.
I get a 400 status code error from a GitHub Pages deployment
During an automated «pages build and deployment» workflow, I get the following error:
Error: Request failed with status code 400
I’ve opened a ticket on GitHub support, but in case anyone here can help me in the meantime. Is there anything I can do to try to resolve this?
1 Answer 1
It could be the side-effect of (from two days ago)
GitHub Pages: using GitHub Actions for builds and deployments for public repositories
Today you will begin to see a new workflow running called pages build and deployment in your public GitHub Pages repositories.
This workflow is automatically triggered when you push to the branch configured for GitHub Pages in your repository.
As the name suggests, it builds and deploys your pages site.
The initial benefit of this change is enabling you to see your build logs and any errors that may occur which has been a long standing issue for Pages users.
However, in the future this will enable us to give you the ability to fully customize your pages build and deployment workflow to use any static site generator you want without having to push the build output to a special branch of the repository.
Learn more about GitHub Pages
So Cecilapp/GitHub-Pages-deploy (the GitHub Pages deploy) workflow you might be using) might behave differently in light of those recent changes.
«HTTP 400 Bad Request» error when proxying HTTP requests from an Exchange Server to a previous version of Exchange Server
Symptoms
When a user tries to proxy an HTTP request from a Microsoft Exchange Server 2016 server that is running client access service or a Microsoft Exchange Server 2013 Client Access server (CAS) to a previous version of Exchange Server, the user may receive the following error message:
This error (HTTP 400 Bad Request) means that Internet Explorer was able to connect to the web server, but the webpage could not be found because of a problem with the address.
Additionally, the HTTPERR logs on the Microsoft Exchange Server 2010 or Microsoft Exchange Server 2007 Client Access server may show one of the following for the HTTP resource the user was requesting:
Also, you may see the following in the Exchange Server \Logging\HttpProxy\ logs on the Exchange Server 2013 Client Access server:
Cause
This issue may occur if the user is a member of many Active Directory groups. This issue may occur during the proxy process from Exchange Server 2016 or Exchange Server 2013 CAS to Exchange Server 2010 CAS.
Resolution
To fix this issue, use one of the following methods:
Reduce the number of Active Directory groups that are assigned to the user.
On every Exchange 2010 CAS, locate the following subkey:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters
Under this subkey, increase the MaxFieldLength and MaxRequestBytes entries by using the values in the following table.
Value name | Value type | Value data | Value base |
---|---|---|---|
MaxFieldLength | DWORD | 65536 | Decimal |
MaxRequestBytes | DWORD | 65536 | Decimal |
Notes
More Information
Changing these registry keys might be extremely dangerous. Increasing the values allow larger HTTP packets to be sent to IIS, which in turn might cause Http.sys to use more memory and might increase vulnerability to malicious attacks.
The recommended value for Exchange Server coexistence is 65536.
The value should be 65536 for Exchange Server. It should not be 65534, as indicated in KB 2020943. That setting is for Internet Information Services (IIS). This difference is because of additional requirements for Exchange Server.
In some cases, a MaxFieldLength value of 65536 may not fix the issue. If this occurs, we recommend that you reduce the size of the user’s access token by removing groups instead of increasing the value.
Increasing the value of MaxRequestBytes to be greater 65536 has risks. Therefore, we do not recommend that you do this. These risks are discussed in detail in KB 820129. This key is assigned a warning code of 1 to indicate a high risk for changing the default value.
400 Bad Request: The SSL certificate error
I get this error when I try to get page with client key and certificate using this command:
Here’s what I see in nginx logs:
And here is part of my nginx.conf:
Here are the commands I’ve used to create client cert:
What could be wrong here? Should I use some other certificate as CA for my client cert than server cert?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
First of all, enable debug log in nginx.conf :
And restart nginx. Then repeat the request and check the log file. Find the first line with verify:0 :
Alternatively you can verify the certificate using openssl command line tool:
If you’re getting error 20 specifically and your client certificate is self-signed, you might have encountered this bug. To fix it you should either drop keyUsage from your certificate entirely or add keyCertSign to the list. To verify whether you’ve stumbled upon it, check whether Key Usage is listed in X509v3 extensions: section in the output of the following command:
Getting 400 bad request error in Jquery Ajax POST
I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
Here is my code:
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:
May be it will help someone else.
Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.
Bad Request. Your browser sent a request that this server could not understand.
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
I needed to add the attributes to the controller:
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
The question is a bit old. but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
and pass them in your request
You need to build query from «data» object using the following function
and then proceed with
I’m hoping this may be of use to those encountering 400 errors while using AJAX in WordPress going forward. Even though this question is many years old, the solutions provided have all been programmatic, and I’m sure many have stepped through their code to repeatedly find it’s correct, yet continue to find it is not working.
I found dozens of results asking how to resolve «WP AJAX request returning 400 Bad Request» or «WP AJAX request returning 0» and nothing today worked.
Googling «How do I fix 400 bad request on WordPress?» finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/
Clear your Web Browser Cache and Cookies
You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser’s cache and cookies. Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.
Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.
Что означают ошибки 400, 403, 404, 500, 502, 503 и как их исправить?
Читайте о самых распространённых онлайн ошибках. Какие причины их возникновения и как исправить.
Введение
В пользование сетью «Интернет» вовлечено подавляющее большинство всех обладателей компьютерной техники, независимо от вида используемых образцов устройств. И несмотря на многие преимущества задействования «Интернета» как для обработки и хранения данных, так и для их распространения и обмена, в некоторых случаях существует вероятность столкнуться с отказом в доступе к тем или иным ресурсам сети по причине возникновения разнообразных видов ошибок. И несмотря на утверждение, что полностью избежать ошибок в целом при взаимодействии с данными в сети «Интернет» практически невозможно, пользователи могут ознакомиться со списком основных и часто встречающихся видов ошибок, понять их значение и изучить некоторые основные шаги для их устранения. И далее в нашей статье мы подробнее остановимся на освещении данных вопросов.
Распространенные типы сетевых ошибок при доступе к ресурсам сети «Интернет»
Большинство известных видов ошибок в сети «Интернет» сопровождаются кодом состояния «HTTP». Обычно пользователи могут наблюдать сообщение об ошибке, содержащее помимо объясняющего текста еще числовое значение формата «4XX» или «5XX» (за числами четыре или пять следуют две дополнительные цифры, например, код ошибки имеет вид «404»).
И вариант формата «4XX», и «5XX» являются ошибками, но они имеют существенную разницу. Формат «4XX» – это ошибки, возникающие вследствие деятельности клиента, а «5XX» – результат ошибки сервера. Если при обращении к сетевому ресурсу всплывает сообщение с ошибкой в виде «4XX», то, скорее всего, пользователи могут ее самостоятельно исправить.
Ошибки вида «5XX» – это ошибки сервера, которые означают, что пользователи не оказывали влияния на результат, приведший к возникновению ошибки, и источником сбоя является неработающий сервер, к которому пользователи пытаются получить доступ. Независимо от вида ошибки, связанна ли она с деятельностью пользователей или работоспособностью удаленного сетевого сервера, пользователи могут предпринять несколько шагов, которые могут помочь решить проблему и устранить существующую неисправность.
В последующих разделах мы постарались перечислить наиболее распространенные сетевые ошибки, с которыми могут сталкиваться пользователи при взаимодействии с ресурсами сети «Интернет», а также упомянули пару полезных решений для исправления каждой ошибки. Пользователи не могут решить все онлайн-ошибки, так как некоторые из них происходят по вине серверов, и с ними мало что можно поделать для успешного восстановления работоспособности. Тем не менее, в ряде случаев, стоит попробовать устранить возникшую ошибку.
«400 Bad Request» («ошибка неверного запроса»)
Каждый раз, когда пользователи пытаются открыть веб-сайт путем набора «URL-адреса» в адресной строке сетевого обозревателя или нажимают на соответствующую ссылку сайта, полученную посредством различных приложений, веб-браузер инициирует запрос и отправляет его на удаленный сервер веб-сайта, к которому пользователи организовывают соответствующее обращение и стараются получить доступ. Ошибка «400» возникает, когда сервер не может полноценно понять и корректно обработать запрос. Такой вид непредвиденной ошибки может произойти, если указанный запрос искажен, неверен, испорчен или поврежден, но, чаще всего, ошибка возникает по довольно простой причине, например, пользователь использовал «URL-адрес» веб-сайта, которого не существует.
В большинстве случаев пользователи самостоятельно могут решить возникшую проблему и далее представлено несколько простых способов, которые можно задействовать для исправления указанной ошибки.
Обновите страницу. Нажатие клавиши «F5» обновляет страницу в большинстве браузеров. Если проблема связана с поврежденным запросом, то его повторная отправка иногда может помочь. Процесс не займет много времени и его всегда стоит попробовать. Ошибка «400» часто является временной, и простое обновление способно нередко ее исправить.
Перепроверьте «URL- адрес». Иногда неверный «URL-адрес», указанный пользователем в адресной строке обозревателя, может вызвать ошибку «400 Bad Request» вместо ошибки «404 Not Found» (о которой мы также поговорим в одном из разделов). Просмотрите и исправьте адрес при необходимости.
Произведите поиск страницы на сайте. Возможно, ошибка в названии веб-страницы искомого сайта была допущена самим пользователем или непосредственно неверный адрес был указан в ссылке, с которой осуществлен переход на страницу. Но если страница на сайте существует, то можно в строке поиска веб-сайта указать части полного адреса страницы, чтобы получить к ней доступ через поисковую панель.
Очистите файлы «cookie» и содержимое кэша используемого веб-браузера. Иногда, при обращении к веб-сайту, от сервера возвращается ответ с ошибкой «400», потому что происходит попытка прочесть «cookie» на пользовательском компьютере, которые повреждены или сильно устарели, или, как вариант, браузер кэшировал поврежденную версию страницы, которую пользователь пытается открыть. Своевременная очистка данных кэша и файлов «cookie» может помочь исправить неприятную ошибку.
«403 Forbidden» (ошибка «запрещено»)
Ошибка «403» возникает при попытке доступа к странице или сетевому ресурсу, к которым у пользователя нет соответствующего разрешения. В большинстве случаев, устранить проблему запрета доступа силами конкретного пользователя не получиться. Обычно подобное сообщение об ошибке возникает по одной из двух причин. В первом случае, владельцы веб-сервера корректно настроили права доступа, а пользователь действительно не обладает соответствующими допусками для перехода на удаленный ресурс. В другом случае, причина заключается в том, что собственники веб-сервера неправильно настроили разрешения (случайно или преднамеренно), и пользователь получает отказ в доступе, когда он действительно необходим, даже при наличии необходимых привилегий.
Несмотря на тот факт, что ошибка «403», ограничивающая доступ к удаленному ресурсу, регулируется и управляется настройками сетевого веб-сервера, пользователи могут опробовать несколько шагов для ее исправления.
Обновите страницу. Нажатие клавиши «F5» во многих популярных обозревателях позволяет мгновенно обновить страницу.
Повторно проверьте «URL- адрес». Иногда неверно заданный в строке обозревателя «URL-адрес» может вызвать появление ошибки запрета доступа «403 Forbidden». Убедитесь, что «URL-адрес» действительно указывает на страницу, а не на каталог. Большинство веб-сайтов ограничивают доступ к своим внутренним папкам из соображений безопасности, и опечатка в адресе может быть причиной отображения ошибки «403».
Проверьте собственные разрешения. Некоторые веб-сайты ограничивают доступ к своему содержимому, разрешая удаленное обращение только зарегистрированным участникам или пользователям, обладающим определенным уровнем привилегированного доступа. Если вход в систему не был осуществлен или у пользователей нет соответствующих разрешений, то, скорее всего, система выдаст ошибку «403 Forbidden».
«404 Not Found» (ошибка «не найдено»)
Ошибка «404 Not Found» – самая распространенная ошибка в сети, которая возникает при попытке посетить несуществующую веб-страницу. В основном, данная ошибка подразумевает, что серверу не удалось найти, искомый пользователями, удаленный ресурс. В большинстве случаев, в обозревателе появится сообщение об ошибке «404» после неудачной попытки ввести «URL» искомой страницы или перейти по соответствующей ссылке, которая на сервере абсолютно не представлена. И если пользователи сталкиваются с ошибкой «404», то можно попробовать ее исправить несколькими способами.
Обновите проблемную страницу. Нажатие клавиши «F5» инициирует обновление страницы в подавляющем большинстве современных веб-браузеров. Не всегда такое решение сможет устранить ошибку «404». Но иногда, на веб-серверах может происходить случайный сбой и, как следствие, отображение страницы, которая действительно существует, будет временно приостановлено. Поэтому необходимо обязательно опробовать данный способ и перегрузить страницу, в особенности, если на обновление будет потрачено всего несколько секунд, но существует шанс добиться корректной загрузки.
Убедитесь в правильности «URL- адреса». Неверно введенные «URL-адреса» (независимо от того, была ли допущена ошибка в процессе набора или веб-страница содержит неверную ссылку) являются наиболее частой причиной отображения в обозревателе сообщения об ошибке «404 Not Found».
Осуществите поиск требуемой страницы на сайте. Возможно пользователи получили неверный «URL-адрес» или на веб-сайте, с которого был осуществлен переход, указана ошибочная ссылка, но страница на искомом ресурсе существует. Попробуйте найти, посредством использования возможностей поисковой панели сайта, «URL» требуемой страницы по названию.
«500 Internal Server Error» («внутренняя ошибка сервера»)
Если пользователь пытается посетить веб-сайт и на странице веб-браузера всплывает сообщение «500 Internal Server Error», это обычно означает, что на сетевом ресурсе, к которому непосредственно происходит обращение, существует определенная неполадка и сервер не может предоставить более конкретную информацию. Проблема относится только к сайту и никак не связана с настройками и функционированием пользовательского веб-браузера, персонального компьютера или задействованным способом подключения к сети «Интернет».
Как и в случае с другими проблемами, которые мы обсуждали ранее, пользователь можете попытаться решить возникшую неисправность лишь несколькими способами.
Обновите страницу обращения. Большинство распространенных веб-браузеров используют стандартный набор клавиш для быстрого исполнения списка команд, и нажатие на клавишу «F5» позволяет сразу обновить активную страницу. К сожалению, во многих случаях, данный способ не работает по причине неисправности на удаленном ресурсе.
Важное замечание. Не пытайтесь перезагрузить страницу, если перед получением данного сообщения об ошибке «500» была предпринята попытка осуществить онлайн-платеж или любой вид денежного перевода. Принудительное обновление страницы может привести к отправке одного и того же платежа дважды. Большинство веб-сайтов обладают встроенным инструментом защиты и должны препятствовать повторному переводу денежных средств, но проблема может возникнуть, если веб-сайт испытывает проблему во время выполнения платежа.
Обратитесь к ресурсу позже. Довольно часто проблемы с сервером носят временный характер. Попробуйте посетить страницу после небольшого перерыва.
Свяжитесь с администрацией сайта. Если проблема не устранена, попробуйте, при возможности, связаться со службой поддержки веб-сайта, и сообщить им о возникших неполадках.
«502 Bad Gateway» («ошибка шлюза»)
Ошибка «502 Bad Gateway» означает, что посещаемый вами сервер пытался получить некоторую информацию с другого сервера, но получил неверный ответ. Причиной могут послужить несколько факторов. Возможно, сервер перегружен или возникли неполадки с сетью между двумя серверами, что носит временный характер, и может быть быстро исправлено. Также, как вариант, могут оказывать влияние на отсутствие доступа неправильные настройки брандмауэра или даже ошибка кодирования. В довольно редких случаях ошибка может возникать из-за проблемы на пользовательском компьютере или сетевом оборудовании. Поэтому стоит попробовать применить несколько шагов для возможного исправления ситуации.
Обновите страницу после отображения сообщения об ошибке. Как и в предыдущих случаях, воспользуйтесь быстрым способом перезагрузки страницы посредством нажатия в веб-браузере клавиши «F5».
Проверьте, доступен ли сайт для других пользователей. Посетите сайт, такой как «IsItDownRightNow» или «DownforEveryoneorJustMe», который отслеживает состояние веб-сайтов и проверяет их работоспособность для уточнения данных, испытывают ли другие пользователи трудности с доступом к конкретному ресурсу, или проблемы возникают только локально на пользовательском устройстве.
Попробуйте получить доступ к веб-сайту позже. Возможно, проблема с сервером носит временный характер, и спустя некоторое время полноценная функциональность ресурса будет восстановлена. Поэтому попробуйте обратиться к сайту позже через некоторое время.
Выполните очистку «cookie» и содержимого кэша пользовательского браузера. Иногда (хотя и редко) серверы возвращают ошибки формата «502», потому что веб-браузер, который регулярно использует пользователь для выхода в сеть «Интернет», кэшировал устаревшие или поврежденные файлы. Процедура очистки содержимого кэша и файлов «cookie» может помочь исправить ошибку.
«503 Service Unavailable» (ошибка «сервис недоступен»)
Ошибка «503 Service Unavailable» означает, что сервер временно не может обработать запрос пользователя. Ошибка может возникать по ряду причин, но наиболее распространенная, из доступного списка вариантов, состоит в том, что сервер перегружен внешними запросами. Отображение данной ошибки на странице веб-браузера после обращения пользователя фактически означает, что с сервером все в порядке, его работоспособность не нарушена и он может обработать ваш запрос, но чрезмерная нагрузка не позволяет этого сделать в данный момент. Подобно всем ошибкам формата «5XX», ошибка «503» происходит на сервере, и, следовательно, с пользовательским компьютером все в порядке, и он не влияет на ее наличие.
Но несмотря на удаленную форму неисправности, можно попробовать применить несколько способов для устранения ошибки.
Обновите страницу с сообщением об ошибке. Нажмите на клавишу «F5» и принудительно обновите проблемную страницу (стандартный способ перезагрузки поддерживается многими основными веб-браузерами).
Проверьте работоспособность ресурса. Перейдите в веб-браузере на сайт проверки состояния удаленных ресурсов, например, «IsItDownRightNow» или «DownforEveryoneorJustMe», и оцените его доступность для других пользователей.
Попробуйте выполнить переход на сайт позже. Проблемы с сервером часто бывают временными. В частности, при отображении сообщения с ошибкой «503», велика вероятность, что сервер перегружен запросами и не может обработать все входящие обращения, который он получает. Попробуйте посетить страницу еще раз позже через некоторое время.
Полную версию статьи со всеми дополнительными видео уроками смотрите в источнике. Если у вас остались вопросы, задавайте их в комментариях.
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
ASP.NET Web Api HttpResponseException 400 (Bad Request) Hijacked by IIS
I’m writing a Web API service and trying to return a (400) Bad Request if my ModelState is invalid. I do not want a response body to be attached to this. It appears that IIS is hijacking my response and always returning a text/html content type with a lengthy, styled error page. This is a problem.
Here is my fiddler request:
And my response erroneous, full of body, response:
I have tried to set TrySkipIisCustomErrors = True with great hope, but no luck. Any ideas? Appreciated. Thanks.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Try adding this to your web.config. I had a very similar problem which this solved.
Usually in such cases it is enough to set TrySkipIisCustomErrors = true on response object, but in case of Web API it sometimes doesn’t do the trick (Web API even tries to set this flag internally by itself). For situations like this you can consider changing the IIS configuration. Please take a look here (you should be mostly interested in existingResponse=»PassThrough»).
Assuming you’re inside of your APIController and don’t need an ExceptionFilterAttribute to do any additional work for the response, then just return a response with the error status code instead of throwing an HttpResponseException.
I had the same problem with Asp.Net Webform application. The client sends ajax call to the server web handler (*.ashx).
I wanted to get the exception message back to the user. The Web handler sends back just the exception message and http status code 400.
The Trick is in Response.TrySkipIisCustomErrors = true;
I was hitting this same condition, returning:
Adding didn’t fix it, Content-type and the content body were missing in the response.
What did fix it was to construct the HttpResponseMessage like this:
By including the ‘value’ parameter (in this case, ‘reasonPhrase’) the Content-type and Content Body were present in the response.
I had a situation where I was calling a WebApi endpoint from another, and having read that HttpClients should be static I made that change. Worked fine for a few dozen messages but then would get intercepted by the self-host instance which would return a 400 Bad Request. There didn’t seem to be anything wrong, especially with the initial success, but my original code would add a default header to the client prior to the call. After I made the client static this would have meant that I was adding the header multiple times to the same client. I changed the code to send create and send an HttpRequestMessage instead of letting the client do it, and added the header to the request. Seems to have solved my problem.
Request failed with status code 400 with axios
I am trying to use the login API I made using node, however, whenever I call the API using Axios, it gives me a request failed in the console.
This is how I use axios to call my method:
And this is my login page and console :
This is my backend configuration:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
please try this
well, I do not know how is the backend configured, but you could start by stringyfing yow body
If that does not do any change, then change the header instead
Коды ответов сервера — подробное описание
В статье:
При каждом обращении к серверу вы получаете от него код статуса ответа. Коды связаны с функциональностью страниц сайта и сигнализируют о состоянии страницы. Благодаря значению, которое несет код, сервер корректирует обработку документа после запроса пользователя. Самые популярные коды — 200, который показывает, что запрос выполнен успешно, и 404, показывающий ошибку, если ресурс не найден.
На код ответа сервера обращают внимание поисковые боты и браузеры.
Как проверить код ответа сервера
Посмотреть код ответа на странице можно бесплатно за пару кликов. В браузере информация находится на панели разработчика: в Google Chrome для вызовите панель горячей клавишей F12, откройте вкладку Network и обновите страницу.
Результаты просмотра кода в браузере
Для просмотра кода есть браузерные расширения: HTTP Headers для Google Chrome, HTTP Header для Opera.
Результаты проверки инструментом
Инструмент проверки заголовков сервера от PR-CY определит HTTP статусы сайта и доменного имени.
Результаты проверки инструментом
Значения кодов ответов сервера
Код состоит из трех цифр и начинается с 1-5 в зависимости от группы, к которой принадлежит. После числового обозначения есть приписка на английском, которая поясняет его значение.
Принадлежность кода к группе определяется по первой цифре:
Коды ответов, сигнализирующих об ошибке, содержат информацию об их причинах. Отслеживать ошибки и устранять их можно по лог-файлам сервера — в логах содержится детальная информация о проблемах.
Информационные коды
Коды этой группы информируют о том, что сервер принял запрос и будет его обрабатывать.
100 Continue
Сервер принял запрос и удовлетворен начальными сведениями. Процесс обработки будет продолжен.
101 Switching Protocols
Сервер одобрил переключение типа протокола, которое запросил пользователь. Код используется, когда сервер предлагает перейти на новую версию HTTP. В поле Update будут перечислены доступные протоколы, пользователь может выбрать один из них.
102 Processing
Сервер сигнализирует, что принял запрос, но на обработку требуется больше времени. Клиенту не нужно разрывать соединение, он должен сбросить таймер и дождаться следующей команды.
Коды успешной обработки запроса
Коды группы сигнализируют о том, что запрос принят и успешно обработан.
200 ОК
Это один из самых популярных ответов, он означает, что запрос принят и успешно обработан, страница открыта и доступна к просмотру. Все страницы, которые будут проиндексированы, должны отдавать код 200 ОК.
201 Created
Ответ означает, что сервер принял запрос, обработал и создал новый ресурс. Код можно увидеть, к примеру, если пользователь создал новую страницу. Если новый ресурс создать невозможно, или он перестанет существовать к тому времени, когда клиент получит сообщение, то сервер отдаст код 202 Accepted.
202 Accepted
Сервер принял запрос, но не завершил его обработку. Запрос можно отклонить, поскольку на его выполнение может потребоваться слишком много времени.
203 Non-Authoritative Information
Код ответа 203 означает, что операция прошла успешно, но от кода 200 он отличается указанием источника информации. Данные получены не из первоисточника, а с другого сервера или резервной копии. Возможно, информация устарела, о чем и предупреждает код ответа.
204 No Content
Обработка запроса прошла успешно, но серверу нечего отправить в ответ. Ответ не содержит тело сообщения, только заголовки. Обычно такой код включается в первую пустую строку кода, чтобы разрешить запуск скриптов, не меняя содержимого и не обновляя страницу.
205 Reset Content
Сервер сигнализирует, что запрос успешно обработан и клиенту нужно сбросить введенные данные. Обновление документа не требуется, сервер не передает тело сообщения.
206 Partial Reset
Этот код обычно используют инструменты кэширования. Сервер в ответе возвращает только часть контента страницы, которую и запрашивает пользователь.
207 Multi-Status
Код обозначает мультистатусность ответа: сервер обработал несколько операций,не зависящих друг от друга. Результаты отображаются в теле сообщения как XML-документ с объектом multistatus.
226 IM Used
Сервер успешно завершил операцию: принял заголовок A-IM и вернул содержимое с учетом указанных параметров.
Коды редиректов
Класс кодов показывает, что для успешного выполнения запроса клиенту нужно совершить переход, то есть редирект.
300 Multiple Choices
Робот не может проиндексировать страницу, поскольку не может сопоставить ресурс и URL. Частая причина — ресурс перемещен на другой адрес. Сервер предлагает клиенту выбор альтернатив для перехода. Для успешной индексации нужно либо правильно указать ресурс, либо поправить заголовки.
301 Moved Permanently
Если у проиндексированной страницы изменился адрес, то со старого URL на новый настраивают 301 редирект. Код ответа показывает, что запрашиваемый документ был навсегда перенесен на другой URL, куда пользователя перенаправляет ссылка. Робот проиндексирует страницу, на которую ведет редирект, и склеит исходный адрес и новый.
302 Found
Код означает не постоянное, а временное перемещение страницы на другой адрес, поэтому страницу удалять из индекса не нужно. В ответе указано новое расположение данных.
Страница остается в индексе, ссылочный вес продолжает передаваться.
303 See Other
Сервер сигнализирует, что ресурс, который указан в запросе, расположен на другом адресе. Обычно он используется для перенаправления пользователя к выбранному ресурсу выводом данных POST-активированного скрипта.
В ответе сервера будет указан адрес, по которому нужно искать результат, удовлетворяющий запрос.
304 Not Modified
Код рекомендуется выдавать, если страница не менялась с момента ее последнего посещения роботом. Сервер дает сигнал об этом боту, бот получает от документа http-заголовки, не загружая страницу повторно, из-за чего индексирование проходит быстрее и уменьшается нагрузка на сервер.
305 Use Proxy
Код ответа связан с безопасностью данных. Сервер выдает код 305, если доступ к ресурсу, который запрашивает клиент, возможен только с прокси. Прокси указан там же в ответе сервера.
307 Temporary Redirect
Код 307 похож на 302, но дает более конкретный ответ. Код означает, что ресурс, который требует клиент, на время переведен на другой адрес, а новый URL нужно прописать в Location.
Коды ошибок клиента
Коды ответов этой группы означают ошибки по вине клиента или невозможность выдать результат, потому что на странице нет данных.
400 Bad Request
Запрос некорректен, где-то в нем есть синтаксическая ошибка, поэтому сервер не может выдать результат. Для успешного выполнения запроса нужно исправить синтаксис, обычно помогает очистка куки или кэша страниц, исправление запроса пользователем.
401 Unauthorized
Информация доступна только зарегистрированным пользователям или запаролена. Если пользователь не авторизовался, доступ к странице невозможен.
403 Forbidden
Если пользователю www-data, под которым запущен сервер, закрыт доступ к чтению файла, поможет команда sudo chmod o=r /usr/share/nginx/html/index.html
Еще одна причина — пользователь обратился к закрытому каталогу, в котором нет индексного файла. Разрешение на просмотр каталога включается в настройках сервера.
404 Not Found
Серверу не удалось найти ресурс, который запрашивает пользователь, документа по этому адресу не существует.
Это частая ошибка, она может быть связана с тем, что пользователь ошибся в адресе страницы, у пользователя нет прав на чтение и исполнение файла, файл на сервере переместили иди удалили, корневой каталог указали с ошибкой или сервер не настроен для работы с символьными «мягкими» ссылками, которые использованы для обработки.
Код ответа 404 Not Found
Ссылки на удаленные разделы сайта будут возвращать код 404. На такие документы не нужно тратить краулинговый бюджет, поэтому в файле robots.txt запрещают роботу посещение и индексацию таких страниц.
405 Method Not Allowed
Недоступен метод, которым совершается запрос. Сервер выдает этот код для конкретных отдельных объектов на странице. К примеру, строка запроса, запускающая скрипт, отличается от запроса, который совершает пользователь.
406 Not Acceptable
Код ответа означает, что запрашиваемый файл существует, запрос сформулирован верно, но кодировка документа недоступна для расшифровки роботом.
407 Proxy Authentication Required
Этот код похож на 401 и 407, он используется, если вопрос корректен, но клиент может получить доступ к документу только с помощью авторизации через прокси. Клиент авторизуется, если прокси вернет поле с заголовком proxy-authenticate.
408 Request Timeout
Сервер возвращает этот код ответа, если в установленное время ожидания клиент не сделал ни один запрос. Код 408 не возвращается, если пользователь сам отменил запрос, или соединение оборвалось, а отправить ответ нет возможности.
409 Conflict
Код означает, что в системе конфликт: к примеру, пользователь загружает файл на сервер, где уже есть такой файл в новой версии.
410 Gone
Код ответа похож на 404 код, он означает, что документ, к которому направлен запрос, больше недоступен. Если сервер возвращает код 404, то робот еще вернется на страницу, чтобы проверить ее состояние, а в случае ответа 410 робот поймет, что страница удалена навсегда.
411 Length Required
Сервер не может принять и обработать запрос, если в заголовке content-length не указана длина контента.
413 Request Entity Too Large
Если в теле запроса слишком большой объем информации и сервер не может обработать такой большой запрос, то он возвращает код ошибки 413. Если это временная проблема, в поле Retry-After сервер укажет время, которое нужно подождать.
414 Request-URL Too Long
Аналогично с кодом 413, за исключением того, что 414 код отображается, если в запросе указан слишком длинный URL.
422 Unprocessable Entity
Сервер возвращает этот код, если он принял и распознал запрос, но в теле запроса допущена логическая ошибка, которая мешает его выполнить.
424 Failed Dependency
Если выполнение этой операции зависит от исхода других связанных с ней операций, сервер вернет этот запрос.
429 Too Many Requests
Код 429 означает, что пользователь посылает слишком много запросов за короткий временной промежуток, и сервер не может обработать такое количество.
431 Request Header Fields Too Large
Если в запросе указаны слишком большие поля заголовков, сервер не сможет справиться с таким запросом и вернет код ошибки 431.
451 Unavailable For Legal Reasons
Код отображает то же, что и 403, но с уточнениями. Он используется, если доступ к серверу заблокирован по решению суда, обычно из-за нарушения авторских прав, а также если доступ закрыт на государственном уровне.
418 I’m a teapot
Это забавный код, возвращающий ошибку «Я чайник», связан с гипертекстовым протоколом управления кофеваркой — Hyper Text Coffee Pot Control Protocol. Ошибка означает, что запрос некорректен, с помощью чайника нельзя приготовить кофе. Протокол и код этой ошибки были созданы в шутку в 1998 году к 1 апреля.
Код 418 I’m a teapot
Коды ошибок сервера
Коды этой группы обозначают ошибки на стороне сервера.
500 Internal Server Error
501 Not Implemented
Сервер возвращает этот код, когда не может обработать запрос: он не поддерживает возможности для обработки или не может распознать метод. К примеру, эта ошибка появится, если распространенные протоколы HEAD, POST, GET и другие по какой-то причине не поддерживаются сервером.
502 Bad Gateway
За обработку запроса отвечают бэкенд серверы, которые передают данные прокси-серверу или шлюзу. Если запрос был направлен к такому шлюзу, который не получил ответ от бэкенда, сервер вернет 502 код. Для исправления нужно проверить настройку прокси-сервера.
503 Service Unavailable
Код свидетельствует о перегрузке сервера, запрос не может быть выполнен в данный момент. Второй причиной может быть обслуживание сервера: ему не хватает памяти или ресурсов, чтобы обработать запрос. Такой ответ может вернуться, если на сервере ограничено количество пользователей.
504 Gateway Timeout
Код похож на 502, но ошибка 504 означает, что истек срок ожидания ответа от сервера. Необходимое количество времени истекло, а ответ от бэкенд-сервера не пришел.
Причина может быть в сетевом соединении, недостатке ресурсов, версии протокола HTTP или настройке сервера, если выставлен слишком короткий таймаут.
506 Variant Also Negotiates
Код ответа 506 означает, что сервер настроен некорректно: ошибка в конфигурации зацикливает обращение сервера, и он указывает сам на себя.
507 Insufficient Storage
Если сервер загружен настолько, что для выполнения запроса не хватает памяти, он вернет ошибку 507. Это бывает, если на сервере нет места для данных в принимаемом запросе.
510 Not Extended
Код 510 возвращается в случае, если сервер не поддерживает расширение, которое указано в запросе. В этом же ответе сервер может указать, какие расширения доступны.
511 Network Authentication Required
Эта ошибка возвращается клиенту, если пользователь не авторизовался в сети. К примеру, если он не согласился на условия использования интернета, когда подключался к wi-fi, или не ввел пароль.
На коды ответов сервера обращают внимание поисковые роботы, с помощью этих сигналов они узнают, как им нужно вести себя со страницей — индексировать, пропустить, вернуться к ней позже. Веб-мастерам важно распознавать сигналы с ошибками, чтобы направлять поисковых ботов и исправлять часть ошибок, если причина ошибки им доступна.
400 Bad requests
I am using Spring Boot 1.2 There is FrontEnd Web application and Backend Web application. FrontEnd Web application is built with Angular and Spring Boot 1.2. FrontEnd Web application is built with Spring Boot 1.2.
The FrontEnd Web application using RestTemplate to invoke BackEnd Web application. All GET requests using RestTemplate from FrontEnd Web application to BackEnd Web application works fine all the time.
The POST requests using RestTemplate are not working all the time. Out of 10 POST requests, 1 POST request results in 400 BAD REQUEST.
The POST requests always posts JSON. RestTemplate has been configured to set «Accept» («application/json») and «Content-Type» («application/json») headers.
The error throws by RestTemplate is
Any insight would be greatly appreciated. Is Spring throwing this exception or Tomcat throwing this exception?
FrontEnd application has following end-point:
BackEnd application has following end-point:
Админу.Ру
Библиотека вебмастера по созданию и продвижению сайта
Коды статусов HHTP 4xx (ошибки клиента)
Группа кодов статусов HTTP 4хх отвечает за ошибки на стороне клиента, иными словами, посетителя сайта. К данным статусам следует относиться очень внимательно, так как подавляющее большинство ошибок возникает из-за недоработок вебмастера сайта. Это неверное указание URI документов (например, из-за перепутывания абсолютной и косвенной адресации), указание в открытом доступе ссылок на защищённую часть сайта, неверная настройка HTTP-сервера и ещё много других нюансов и тонкостей.
Коды статусов HHTP 4xx (ошибки клиента)
Устранить эти недоработки вы сможете грамотно анализируя серверные логи доступа, настроив обратную связь с посетителями своего сайта, а также внутренним тестированием сайта на разных платформах, в разных браузерах с различающимися настройками.
Код статуса HTTP 400 Bad request (400 Неверный запрос)
Описание: Запрос не был понят/распознан сервером из-за некорректного синтаксиса.
Код статуса HTTP 401 Unauthorized (401 Неавторизованный запрос)
Описание: Для доступа к содержимому по указанному запросу необходимо быть зарегистрированным пользователем (авторизованным).
Код статуса HTTP 402 Payment Required (402 Необходима оплата запроса)
Описание: Внутренняя ошибка или ошибка в конфигурации сервера.
Код статуса HTTP 403 Forbidden (403 Доступ к ресурсу запрещён)
Описание: Доступ к ресурсу (документу, странице) запрещён сервером.
Совет: Если вы хотите, чтобы ваш ресурс индексировался, необходимо разрешить доступ к нему.
Код статуса HTTP 404 Not Found (404 Ресурс не найден)
Описание: Ресурс (документ, страница) не найден, не существует, сервер не находит его по указанному адресу.
Совет: При удалении какого-либо раздела или документа с сайта, вы можете добавить в файле robots.txt его в список запрещённых для индексирования.
Код статуса HTTP 405 Method not allowed (405 Недопустимый метод)
Описание: Для указанного в строке запроса клиентом ресурса недопустимо применять текущий метод.
Код статуса HTTP 406 Not acceptable (406 Неприемлимый запрос)
Описание: Запрашиваемый ресурс (документ, страница) существует, но нет возможности его отобразить/получить (например, кодировка не поддерживается роботом/браузером).
Код статуса HTTP 407 Proxy authentication required (407 Требуется идентификация прокси)
Описание: Доступ к запрашиваемому ресурсу возможен только через прокси-сервер, требуется регистрация/идентификация.
Код статуса HTTP 408 Request timeout (408 Истекло время запроса)
Описание: Сайт не передал полный запрос в течение установленного времени.
Совет: Если на вашем сайте установлена громоздкая CMS, требующая большого количества ресурсов или имеющая сложную структуру, потому работающая с задержками, вы можете изменить настройки сервера таким образом, чтобы время жизни запроса было увеличено.
Код статуса HTTP 409 Conflict (409 Конфликт)
Описание: Запрос конфликтует с другим запросом или конфигурацией сервера.
Код статуса HTTP 410 Gone (410 Ресурс больше недоступен)
Описание: Запрашиваемый ресурс (документ, страница) был окончательно удалён с сервера и более недоступен.
Код статуса HTTP 411 Length required (411 Необходимо указать длину)
Описание: Сервер не принимает запрос без дополнительного заголовка Content-Length.
Совет: Исправьте заголовки на сервере так, чтобы пользователю выдавался код 200.
Код статуса HTTP 412 Precondition failed (412 Сбой при обработке предварительного условия)
Описание: Обнаружено несоответствие при проверке на сервере полей заголовка запроса (сбой или ошибка предварительного условия).
Код статуса HTTP 413 Request entity too large (413 Запрос превышает допустимый размер)
Описание: Размер запроса превышает максимально допустимый размер, который может обработать сервер.
Код статуса HTTP 414 Request-URI too long (414 Недопустимая длина URI-запроса)
Описание: Сервер отказывается обслужить запрос, потому что запрашиваемый URI превышает максимально возможную длину интерпретируемого сервером запроса.
Код статуса HTTP 415 Unsupported media type (415 Неподдерживаемый MIME-тип)
Описание: Сервер отказывается обрабатывать запрос, потому что тело имеет неподдерживаемый формат.
Совет: Обратите внимание на список поддерживаемых форматов данных в описание сервера и приведите в соответствие обработчики и скрипты, чтобы подобная ошибка не возникала.
Код статуса HTTP 416 Requested range not satisfiable (416 Запрашиваемый диапазон не может быть обработан)
Описание: Сервер отказался выполнить запрос потому, что в заголовке значение поля Range указывает на недопустимый диапазон байтов.
Код статуса HTTP 417 Expectation filed (417 Сбой при ожидании)
Описание: Сервер отказался выполнить запрос потому, что в заголовке значение поля Expect не соответствует ожиданиям.
Код статуса HTTP 422 Unprocessable entity (422 Необрабатываемый элемент)
Описание: Сервер не в состоянии обработать один или несколько элементов запроса.
Код статуса HTTP 423 Locked (423 Заблокировано)
Описание: Сервер отказался выполнить запрос потому, что один из требуемых ресурсов заблокирован.
Код статуса HTTP 424 Failed dependency (424 Неверная зависимость)
Описание: Сервер отказался выполнить запрос потому, что один из зависимых ресурсов заблокирован.
Код статуса HTTP 426 Upgrade required (426 Требуется обновление)
Описание: Сервер потребовал обновления соединения до SSL, но SSL не поддерживается клиентом.
400(Bad request) status code when making request with axios in reactjs
It’s working when making a request with postman for when trying to with axios in reactjs its showing 400 status code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If there are any errors in data, rest framework does not return 2xx status codes it always returns 400 bad request. It means there are errors in request you sent.
Postman is also receiving 400 bad request but it is showing response data (error messages).
axios treats 400 status code as error so you would have to handle it in catch block. If you want to access response sent with errors you can access it from
HTTP Status Codes and Htaccess ErrorDocuments
I was trying to find an official, authoritative list of HTTP Status Codes but I kept finding lists that weren’t authoritative or complete. So I searched and found my answer in the Apache HTTP Server source code. Once I had the exact HTTP Status Codes and resulting Error Documents sent by Apache, I researched deeper into HTTP Status Codes by reading as many related RFC’s as I could find, and several other software source codes were explored. This is the most authoritative list I know of, if you can do better leave a comment and I’ll update it. Another thing to keep in mind, the Status code number itself is what is used by software and hardware to make determinations, the phrase returned by the status code is for the human only and does not have any weight other than informing the user.. So «503 Service Unavailable», «503 Service Temporarily Unavailable», and «503 Get the heck outta here» are all completely valid.
57 APACHE HTTP STATUS RESPONSE CODES
Once I compiled the list of Apache recognized HTTP Status Codes, I was dying to see them all in action (i.e. the corresponding ErrorDocument). At first I thought I would have to create a php or perl script emulating each of the 57 HTTP Status Codes, a tedious undertaking I wasn’t about to do. Instead I «asked Apache» by searching the Apache HTTP Documentation for ambiguity sending Status Codes and/or triggering ErrorDocuments with an Apache Directive.
While reading up on mod_alias and the Redirect directive I found:
Syntax: Redirect [status] URL-path URL The status argument can be used to return other HTTP status codes. Other status codes can be returned by giving the numeric status code as the value of status. If the status is between 300 and 399, the URL argument must be present, otherwise it must be omitted.
1xx Info / Informational
2xx Success / OK
3xx Redirect
4xx Client Error
5xx Server Error
Quick Start to triggering ErrorDocuments for each Status Code
Automate the ErrorDocument Triggering
The htaccess Redirects
When a Status code is encountered, Apache outputs the Header and the ErrorDocument for that error code. So you can view any Header and the default ErrorDocument, by causing that numerical error code, which is caused by the Status Code.
For instance, if you request a file that doesn’t exist, a 404 Not Found Header is issued and the corresponding ErrorDocument is served with the 404 Not Found Header.
PHP script that gets and outputs the Headers/Content
Now all I have to do is add 57 Redirect Directives to my htaccess, and then request each of them 1 at a time from my browser to see the result, and use a packet sniffing program like WireShark to see the Headers. Uh, scratch that, that would take way too long!
Instead I hacked up a simple php script using cURL to automate sending GET Requests to each of the 57 Redirect URL-paths. A side benefit of using the php script is that it performs all 57 Requests concurrently and saves each Requests returned headers and content to an output buffer. After all 57 have been queried, the output buffer is flushed to the browser.
Интернет-серферы очень часто сталкиваются с проблемой того, что вместо предполагаемой страницы при открытии ресурса в веб-браузере выдается ошибка 400, содержащая описание неправильного запроса. Как считается, данный сбой относится к разряду пользовательских, причем связанных с ошибками ввода адреса запрашиваемого ресурса, но это не всегда так.
Изначально саму ошибку можно трактовать именно как неправильный запрос, когда интернет-серфер вводит некорректный адрес ресурса. Это так называемая ошибка синтаксиса. Например, при попытке доступа к почтовому серверу Mail.Ru украинский пользователь совершенно запросто может ввести домен UA вместо RU, справедливо полагая, что изначально сайт может производить переадресацию в зависимости от региона или местоположения пользователя.
А ведь такого домена на самом деле не существует. Вот и получается, что вместо входа на стартовую страницу серфер и получает сообщение о том, что произошла ошибка 400 (Bad Request – неправильный, некорректный или плохой запрос).
Влияние служб Windows
Одной из причин появления сбоя, как отмечают некоторые специалисты, может стать даже влияние служб, представленных антивирусным ПО и средствами системы защиты самих ОС Windows.
Тот же брэндмауэр (файрвол) или «Защитник» Windows могут запросто спровоцировать ситуацию, когда появляется ошибка 400. В данном случае речь идет о блокировке сайтов и их содержимого. Чтобы устранить такую проблему, в самом простом случае следует внести адрес интернет-ресурса в список исключений всех защитных программ. В случае со встроенным файрволом придется использовать создание нового правила.
Код ошибки 400: Nginx
Нередко появление сообщения об ошибке сопровождается указанием на блокировку со стороны сервиса Nginx. Ситуаций может быть две: либо это вирус, либо действительно сработал оригинальный компонент, который, правда, применяется исключительно в UNIX-подобных системах, и по большому счету к Windows не должен иметь никакого отношения.
Беда в том, что в данном случае производится запрос на сервер, как раз и работающий под управлением подобных ОС, который может блокировать запросы, производимые с конкретного IP-адреса. В свою очередь, сам адрес помечается как ненадежный, и вносится в специальный LOG-файл файрвола, что должно исключить попытки обращений в дальнейшем. Сообщение о том, что произошла ошибка 400, может и напрямую указывать на содержание в системе огромного количества компьютерного мусора в виде кэша и файлов Cookies. Все это нужно почистить.
Что делать в первую очередь?
Во всех случаях, когда возникает ошибка 400, для начала в браузере или с использованием инструментов системы (если по умолчанию доступ к интернету осуществляется через встроенные средства вроде Inetrnet Explorer или Edge) почистить историю посещений, удалить кэш и файлы куки (Cookies). Кстати сказать, применять списки исключений можно только после полной очистки.
Заниматься этим вручную – дело неблагодарное, поэтому для упрощения работы стоит отдать предпочтение автоматическим программам-оптимизаторам (Glary Utilities, Advanced System Care, CCleaner и т. п.).
С другой стороны, стоит проверить систему на предмет наличия разного рода рекламного мусора или шпионских программ, используя для этого не антивирусный сканер, а портативные версии приложений вроде Anti-Malware.
Иногда может помочь даже самая обычная перезагрузка компьютера. Возможно, появление этой ошибки было вызвано кратковременным сбоем операционной системы или используемого по умолчанию браузера (очень может быть, что при доступе к запрашиваемой странице в другом браузере ошибка появляться не будет). В общем и целом, основная часть работы по устранению проблемы сводится к тому, чтобы освободить системные ресурсы и память браузера. После этого проблема исчезает практически во всех случаях, если не считать отсутствие связи или низкую скорость интернет-подключения, когда может наблюдаться таймаут – превышение времени ожидания отклика сервера при запросе. Но это уже другой вопрос, хотя решения, предлагаемые для данной ситуации, помогают и в других случаях, когда проблема связана с запросами в браузерах.
Для тех, кто не желает справляться с проблемой своими силами, создана специальная утилита Fix It от корпорации Microsoft, которая способна исправлять некоторые ошибки подключения к интернету (и не только). Так что пренебрегать и таким инструментом не стоит. В некоторых случаях он может оказаться действенным средством устранения сбоев подобного рода.
React Native to Django Using Axios [Error: Request failed with status code 400]
I have tried almost all options but not getting through. My Django server is working fine with Postman but when I try it from my React Native app, it gives an error
Thanks in advance.
1 Answer 1
Coz you are sending a string to the image field. The value should be a blob type.
it should be something like:
Not sure the uri is working in react native or not. I use rn-fetch-blob for handling blob stuff.
Not the answer you’re looking for? Browse other questions tagged ios django react-native django-rest-framework axios or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
HTTP status code for bad data
What HTTP status code should I return when a client posts bad data (e.g. a string when integer was expected)?
I’ve been using 400 Bad Request, but as I read over the HTTP docs that seems more applicable to HTTP protocol errors.
I’d like to use a status code so that Flash and AJAX clients can distinguish between success, bad data, and server error without having to parse a response.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
This is exactly what 400 is for. Yes, it’s used for bad HTTP protocol usage, but it’s not exclusively for that purpose.
In case of bad syntax use «400 Bad Request»
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
In case of bad data (and correct syntax) use «422 Unprocessable Entity»
Runscope Blog
How to Debug Common API Errors
Introduction
Debugging and troubleshooting APIs is something that any developer that works with APIs has to go through at some point. In an ideal world, APIs would always return a 200 OK with just the right data that we need, or in case of a failure, it would return us the perfect status code and error message allowing us to easily understand what went wrong.
In reality, APIs don’t always work like that. API developers might have constraints that do not allow them to implement the most informative status code or error message, API errors can be triggered by real-world conditions that are hard to account or test for, and sometimes ourselves, as API users, can make requests with typos or mistakes that APIs just don’t know how to handle.
In this post, we’re going to focus on API users and what they can do to debug common API errors they might encounter when testing and working with APIs, whether these APIs are public or private.
Status Codes
We’re going to be focusing on the 4xx client error codes in this post, as they are the more common errors we might see when working with APIs, and which can usually be solved by the API user itself. We’ll also talk a little bit about the 5xx error category at the end.
General Tips
Before we dive into the specifics of a few HTTP status codes, there are certain tips that we can apply to any API debugging attempt.
Use an API Testing Tool
Another advantage of using a tool that allows you to make and replay API requests is they can help you isolate an issue due to a bad API call, or something in your app environment (a configuration issue, firewall, etc.) preventing the API call from returning a 200 status code.
I remember when I first started developing mobile apps, I would sometimes run a Windows Phone app in debug mode and go through several steps to get to an API call I was trying to debug. Don’t be like me.
Read the Docs
I can’t stress this enough, and not only because I enjoy writing documentation, but please read the docs.
I have been guilty of not following this advice as well but, reading the docs can be the difference between being stuck with an issue for 1 hour, or making a successful API call and moving on to your next task.
API documentation, when thorough and well-written, will give you all the answers you might need to successfully work with an API. How to authenticate, how to get an access token, what methods and endpoints are supported, and even what errors you might encounter and how to fix them.
Be Careful with Copy+Pasting
Copy and pasting code snippets from API documentation, or StackOverflow answers, is really easy, but be careful with those.
Examples can be outdated and contain general errors or use an old API version that’s not supported anymore. Copy+pasting code has an even trickier issue where certain characters might completely change how your API call works.
I had an error once where I copy+pasted a piece of text as a query parameter to an API request that should have included a ‘ symbol. Except that the text editor I was using converted the ‘ symbol to a ’ symbol (it might be hard to see, but they are different). When I pasted the text to my API call, that caused it to keep returning a 400 error, and it probably took me 30 minutes to debug.
Now, let’s get to the less general advice, and dig in into specific status codes!
400 Bad Request
A 400 status code means that the server could not process an API request due to invalid syntax. A few possibilities why this might happen are:
A typo or mistake while building out the request manually, such as mistyping the API endpoint, a header name or value, or a query parameter. This can also be caused if the request is missing a required query parameter, or the query parameter value is invalid or missing
A malformed JSON body, for example, missing a set of double-quotes, or a comma. If you need to make an API request with a JSON body, I highly recommend writing it using a linter, whether you use a web editor or code editor plugin
The request is missing authentication information, or the Authorization header provided could not be validated
The main advice when debugging a 400 Bad Request error is to review every piece of text. Make sure there are no typos in the endpoint, headers (name and values), and body. If you copied and pasted any part of your API request, pay extra attention that they don’t include any mistakes or random characters that could be causing an issue.
Our last bullet point above (missing authentication information) is a good example of something you might see when working with multiple APIs. One API might send you a 400 status code for a request that has invalid authentication credentials, while another one might send you a 401 unauthorized status code, which can be used specifically for that purpose.
The 400 bad request status code sometimes is used as a catch-all for multiple types of errors. So if you have checked your API request for any invalid syntax and haven’t found any errors, try to see if any of the other 4xx status code solutions could help you with debugging.
401 Unauthorized
The 401 Unauthorized status code is returned when the API request is missing authentication credentials or the credentials provided are invalid.
APIs can be fickle, and that’s especially true when creating and formatting the Authorization header. OAuth 2 tokens, for example, need to be prepended with «Bearer» for them to work:
It’s also important when using HTTP Basic authentication to pay close attention to the syntax of the header value. The form is as follows:
Http error 400 что за ошибка
Ошибка 400 ( Bad Request) – это код ответа HTTP , который означает, что сервер не смог обработать запрос, отправленный клиентом из-за неверного синтаксиса. Подобные коды ответа HTTP отражают сложные взаимоотношения между клиентом, веб-приложением, сервером, а также зачастую сразу несколькими сторонними веб-сервисами. Из-за этого поиск причины появления ошибки может быть затруднён даже внутри контролируемой среды разработки.
В этой статье мы разберём, что значит ошибка 400 Bad Request ( переводится как « Неверный запрос »), и как ее исправить
На стороне сервера или на стороне клиента?
С другой стороны, ошибка 400 Bad Request означает, что запрос, присланный клиентом, был неверным по той или иной причине. Пользовательский клиент может попытаться загрузить слишком большой файл, запрос может быть неверно сформирован, заголовки HTTP запроса могут быть неверными и так далее.
Мы рассмотрим некоторые из этих сценариев ( и потенциальные решения ) ниже. Но имейте в виду: мы не можем однозначно исключить ни клиент, ни сервер в качестве источника проблемы. В этих случаях сервер является сетевым объектом, генерирующим ошибку 400 Bad Request и возвращающим её как код ответа HTTP клиенту, но возможно именно клиент ответственен за возникновение проблемы.
Начните с тщательного резервного копирования приложения
Подобный подход обеспечит чистую тестовую площадку, на которой можно отрабатывать все возможные сценарии и потенциальные изменения, чтобы исправить или иную проблему без угрозы безопасности или целостности вашего « живого » приложения.
Диагностика ошибки 400 Bad Request
Ошибка 400 Bad Request означает, что сервер ( удалённый компьютер ) не может обработать запрос, отправленный клиентом ( браузером ), вследствие проблемы, которая трактуется сервером как проблема на стороне клиента.
Существует множество сценариев, в которых ошибка 400 Bad Request может появляться в приложении. Ниже представлены некоторые наиболее вероятные случаи:
Исправление проблем на стороне клиента
Ошибку 400 Bad Request ( попробуйте позже ) лучше начать с исправления на стороне клиента. Вот несколько советов, что следует попробовать в браузере или на устройстве, которые выдают ошибку.
Проверьте запрошенный URL
Очистите соответствующие куки
Одной из потенциальных причин возникновения ошибки 400 Bad Request являются некорректные или дублирующие локальные куки. Файлы куки в HTTP – это небольшие фрагменты данных, хранящиеся на локальном устройстве, которые используются сайтами и веб-приложениями для « запоминания » конкретного браузера или устройства. Большинство современных веб-приложений использует куки для хранения данных, специфичных для браузера или пользователя, идентифицируя клиента и позволяя делать следующие визиты быстрее и проще.
Куки хранятся по принципу доменного имени веб-приложения, поэтому можно удалить только те куки, которые соответствуют домену сайта, сохранив остальные куки не тронутыми. Но если вы не знакомы с ручным удалением определённых файлов куки, гораздо проще и безопаснее очистить сразу все файлы куки.
Это можно сделать разными способами в зависимости от браузера, который вы используете:
Загрузка файла меньшего размера
Если вы получаете ошибку 400 Bad Request при загрузке какого-либо файла, попробуйте корректность работы на меньшем по размеру файле, Это включает в себя и «загрузки» файлов, которые не загружаются с вашего локального компьютера. Даже файлы, отправленные с других компьютеров, считаются «загрузками» с точки зрения веб-сервера, на котором работает ваше приложение.
Выйдите и войдите
Попробуйте выйти из системы и войти обратно. Если вы недавно очистили файлы куки в браузере, это приводит к автоматическому выходу из системы при следующей загрузке страницы. Попробуйте просто войти обратно, чтобы посмотреть, заработала ли система корректно.
В большинстве веб-приложений выход повторный вход приводит к перегенерации локального токена сессии.
Отладка на распространённых платформах
Откатите последние изменения
Аналогично, любые расширения или модули, которые были обновлены, могут вызывать ошибки на стороне сервера, поэтому откат к предыдущим версиям этих расширений также может помочь.
Но в некоторых случаях CMS не предоставляют возможности отката к предыдущим версиям. Так обычно происходит с популярными платформами, поэтому не бойтесь, если вы не можете найти простой способ вернуться к использованию старой версии той или иной программной платформы.
Удалите новые расширения, модули или плагины
Проверьте непреднамеренные изменения в базе данных
Расширение может изменить записи в базе данных, которые «не принадлежат» ему, а созданы и управляются другими расширениями ( или даже самой CMS ). В подобных случаях модуль может не знать, как откатить назад изменения, внесенные в записи базы данных.
Я лично сталкивался с такими случаями несколько раз. Поэтому лучшим путём будет открыть базу данных и вручную просмотреть таблицы и записи, которые могли быть изменены расширением.
Поиск проблем на стороне сервера
Проверка на неверные заголовки HTTP
Просмотрите логи
Почти любое веб-приложение будет вести логи на стороне сервера. Они представляют собой историю того, что делало приложение. Например, какие страницы были запрошены, к каким серверам оно обращалось, какие результаты предоставлялись из базы данных и т.п.
Отладьте код приложения или скриптов
Если это не помогло, проблема может быть в исходном коде, который выполняется внутри приложения. Попытайтесь диагностировать, откуда может исходить проблема, отлаживая приложение вручную и параллельно просматривая логи приложения и сервера.
Независимо от причины возникновения ошибки, даже если вам удалось исправить её в этот раз, появление в вашем приложении такой проблемы — это сигнал для того, чтобы внедрить инструмент обработки ошибок, который поможет автоматически обнаруживать их и оповещать в момент возникновения.
О шибка 400 Bad Request возникает, когда запрос, отправленный на сервер сайта, является неправильным или поврежденным, и сервер, получающий запрос, не может его понять. Иногда проблема возникает на самом веб-сайте, и Вы вряд ли сможете что-то сделать. Но большую часть времени проблема заключается в том, что Вы можете решить — возможно, Вы неправильно набрали адрес, или, может быть, Ваш кеш браузера вызывает проблемы. Вот некоторые решения, которые Вы можете попробовать.
Что такое ошибка 400 Bad Request
Ошибка 400 Bad Request возникает, когда сервер не может понять запрос, который был ему отправлен. Это называется ошибкой 400, потому что это код состояния HTTP, используемый веб-сервером для описания такой ошибки.
Ошибка 400 Bad Request может произойти из-за простой ошибки в запросе. Возможно, Вы ошибочно указали URL-адрес, и по какой-то причине сервер не может вернуть ошибку 404. Или, возможно, Ваш веб-браузер пытается использовать истекший или недействительный файл cookie. Некоторые серверы, которые не настроены должным образом, могут также вызывать ошибку 400 вместо более полезных ошибок в некоторых ситуациях. Например, при попытке загрузить файл, который слишком велик для некоторых сайтов, Вы можете получить ошибку 400 вместо ошибки, сообщающей Вам о максимальном размере файла.
Как и при ошибках 404 и 502, дизайнеры веб-сайтов могут настроить, как выглядит ошибка 400. Таким образом, Вы можете увидеть разные страницы ошибки 400 на разных сайтах. Веб-сайты также могут использовать несколько разных имен для этой ошибки. Например, Вы можете увидеть такие вещи, как:
Часто Вы можете сделать что-то, чтобы исправить ошибку 400, но выяснить, что именно может быть сложным из-за неопределенного характера ошибки. Вот некоторые вещи, которые Вы можете попробовать.
Обновите страницу
Обновление страницы всегда стоит того. Многократно ошибка 400 является временной, и простое обновление может помочь. Большинство браузеров используют клавишу F5 для обновления, а также предоставляют кнопку «Обновить» где-то в адресной строке. Это не часто исправляет проблему, но для ее выполнения требуется всего одна секунда.
Дважды проверьте адрес
Наиболее распространенной причиной ошибки 400 является неправильный URL. Если Вы ввели URL-адрес в адресную строку самостоятельно, возможно, Вы ошиблись. Если Вы щелкнули ссылку на другой веб-странице и была показана ошибка 404, также возможно, что в ссылке была опечатка. Проверьте адрес на наличие каких-либо очевидных ошибок. Кроме того, проверьте специальные символы в URL-адресе, особенно те, которые Вы часто не видите в URL-адресах.
Выполнить поиск
Если URL-адрес, который Вы пытаетесь найти, является описательным (или если Вы знаете приблизительное название статьи или страницы, которую Вы ожидаете), Вы можете использовать ключевые слова в адресе для поиска на веб-сайте. В приведенном ниже примере Вы не можете действительно сказать из самого URL-адреса, если что-то не так, но Вы можете увидеть некоторые слова из названия статьи.
Вооруженные этими знаниями, Вы можете выполнить поиск на веб-сайте с соответствующими ключевыми словами. Это должно привести Вас к правильной странице.
Это же решение также работает, если веб-сайт, который Вы пытаетесь достичь, изменил URL-адрес по какой-либо причине и не перенаправил старый адрес на новый.
И если на веб-сайте нет собственного окна поиска, Вы всегда можете использовать Google (или любую другую поисковую систему, которую Вы предпочитаете). Просто используйте оператор «site:» для поиска только соответствующего сайта для ключевых слов.
На изображении ниже мы используем Google и поисковую фразу «site:guidepc.ru локальная сеть» для поиска только сайта guidepc.ru по ключевым словам.
Очистите файлы cookie и кеш браузера
Многие веб-сайты (включая Google и YouTube) сообщают об ошибке 400, потому что куки, которые они читают, либо повреждены, либо слишком стары. Некоторые расширения браузера также могут изменять Ваши файлы cookie и вызывать ошибку 400. Также возможно, что Ваш браузер кэшировал поврежденную версию страницы, которую Вы пытаетесь открыть.
Чтобы проверить эту возможность, Вам нужно очистить кеш браузера и файлы cookie. Очистка кеша не сильно повлияет на Ваш просмотр, но на некоторых веб-сайтах может потребоваться несколько дополнительных секунд для загрузки, поскольку они повторно загружают все ранее кэшированные данные. Очистка файлов cookie означает, что Вам придется снова войти в систему на большинстве веб-сайтов.
Очистите свой DNS
Ваш компьютер может хранить устаревшие записи DNS, которые вызывают ошибки. Простая очистка Ваших записей DNS может помочь решить проблему. Это легко сделать и не вызовет никаких проблем.
Проверьте размер файла
Если Вы загружаете файл на веб-сайт и Вы получаете ошибку 400, то есть вероятность того, что файл слишком большой. Попробуйте загрузить файл меньшего размера, чтобы подтвердить, вызвало ли это проблему.
Попробуйте другие сайты
Если Вы пытаетесь открыть один веб-сайт и получаете ошибку 400, попробуйте открыть другие веб-сайты, чтобы узнать, сохраняется ли проблема. Если это так, это может быть проблемой Вашего компьютера или сетевого оборудования, а не веб-сайта, который Вы пытаетесь открыть.
Перезагрузите компьютер и другое оборудование
Это решение является хитом и перезагрузка компьютера и особенно Вашего сетевого оборудования (маршрутизаторы, модемы) — это распространенный способ избавиться от множества ошибок сервера.
Связаться с веб-сайтом
Если Вы попробовали все решения, и ошибка, не исчезла, значит, сам сайт может иметь проблемы. Попытайтесь связаться с веб-сайтом на странице контактов (если это работает) или через социальные сети. Скорее всего, они уже знают о проблеме и работают над ее исправлением.
Появление ошибки 400 Bad Request при попытке входа на какой-то интернет-сайт – явление весьма распространенное. Причин появления этого сбоя можно назвать достаточно много. А вот исправление возникшей проблемы подразумевает несколько решений, применение которых будет зависеть исключительно от первопричины сложившейся ситуации. Рассмотрим все возможные варианты.
Ошибка 400 http-запроса: причины появления
Как уже понятно, выбирать методику устранения проблемы придется исключительно после выявления причин такого явления. Дело тут даже не в браузере. Для начала попытайтесь просто перевести англоязычное сообщение. Оно дословно означает «плохой запрос». Иными словами, подразумевается обращение к несуществующему ресурсу.
Это самая обычная невнимательность пользователя, который неправильно ввел адрес сайта или вписал окончание доменного имени (например, доступ к сайту Mail.ru будет отклонен при вводе запроса Mail.ru.com или чего-то подобного). Это самая частая проблема.
Но, в основном, среди всего того, о чем может свидетельствовать код ошибки 400, следует выделить следующие первопричины:
Как исправить ошибку 400 простейшим методом
Начнем с последнего пункта. Дело в том, что если проблема действительно связана с удаленным сервером, ничего другого, как выждать некоторое время, а потом попытаться заново повторить попытку доступа, не остается.
Но и сами Windows-системы далеко не безупречны (это известно всем). Появление ошибки 400 может быть связано с кратковременными сбоями и нарушениями в работе ОС, которые критичных последствий для системы в целом не вызывают, но провоцируют невозможность доступа к некоторым интернет-ресурсам.
В этом случае до принятия дополнительных мер рекомендуется просто перезагрузить компьютер или ноутбук и попытаться получить доступ к сайту снова. Вполне возможно, что такой подход и сработает. Но полагаться исключительно на такую методику не стоит (это единичные случаи).
Если в сообщении присутствует ссылка на Nginx, можно смело утверждать, что это действительно проблема, относящаяся к работе сервера под управлением UNIX-систем. Тут ничего не поделаешь. Быть может, работа сервера по истечении какого-то времени будет восстановлена, так что, придется просто ждать.
Очистка временных файлов и Cookies
Основной же ситуацией, когда в браузере вместо открываемой страницы появляется ссылка на ошибку 400, считается наличие в браузере слишком большого количества временных объектов.
Как уже понятно, в данном случае устранить проблему можно совершенно элементарно. Для этого в любом браузере используются пункты очистки истории или что-то похожее, где в обязательном порядке устанавливаются флажки напротив строк очистки временных файлов, файлов Cookies и кэша обозревателя. По окончании выполнения таких действий рекомендуется не только перезапустить браузер, но и выполнить полный рестарт всей системы.
Снятие блокировки со стороны защитных средств
Еще одна достаточно распространенная проблема, связанная с появлением ошибки 400, — блокировка доступа на уровне антивирусного программного обеспечения и встроенных средств защиты самих операционных систем (брандмауэр и «Защитник»).
В первую очередь, необходимо приостановить антивирусную защиту, скажем, минут на десять и проверить возможность доступа. По крайней мере, такая проблема наблюдается с антивирусными инструментами Avast. Если доступ будет восстановлен, либо внесите искомый сайт в список исключений, либо просто смените штатный антивирус на другую программу.
Что касается файрвола, он тоже может провоцировать появление ошибки 400. Его следует отключить, хотя система этого делать и не рекомендует. Все равно попытаться можно. В случае восстановления доступа к ресурсу, файрвол можно оставить отключенным или же в список исключений внести используемый веб-обозреватель.
Проверка на вирусы
Как уже понятно, с вирусами не все так просто. Палка, что называется, о двух концах. С одной стороны, антивирусы могут блокировать доступ, с другой – аналогичные действия могут производить и сами вредоносные коды.
В этом случае необходимо произвести углубленное сканирование компьютера, применяя для этого сканеры портативного типа. Не лишней станет и проверка на предмет наличия в системе вредоносного ПО рекламного характера. В первом случае можно использовать программы вроде Dr. Web CureIt или применить утилиты наподобие Rescue Disk с полной проверкой компьютера еще до старта операционный системы при загрузке со съемного носителя с программой. Во втором случае неплохо подойдет приложение AdwCleaner.
Несколько слов напоследок
Как уже видно из представленного материала, основная проблема появления ошибки 400 связана с мусором, находящимся в браузере. Если его очистка встроенными инструментами обозревателей эффекта не дает, можно воспользоваться специальными программами-оптимизаторами вроде CCleaner, Advanced SystemCare или им подобными. В таких программных пакетах имеются модули очистки (причем даже системного кэша), найти их можно в разделе очистки конфиденциальности.
Но практически в любом приложении есть специальная кнопка быстрой оптимизации, а для ее проведения нужно только отметить нужные пункты, по которым и будет произведена проверка, после которой и произойдет очистка и ускорение работы всей системы.
Наконец, если ни одно из предложенных выше решений не помогло, попробуйте просто сменить обозреватель, используемый для интернет-серфинга по умолчанию, или произведите полный сброс настроек.
What HTTP status code should be used for wrong input
What is optimal HTTP response Code when not reporting 200 (everything OK) but error in input?
Like, you submit some data to server, and it will response that your data is wrong
using 500 looks more like Server Issue
using 200 with warning/error response text is bad (allowing caching and everything is not OK)
using 204 and returning nothing, is maybe good (but well supported?)
using 404 is wrong if requested path (script) is available and in proper place
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Codes starting with 4 (4xx) are meant for client errors. Maybe 400 (Bad Request) could be suitable to this case? Definition in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html says:
«The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. «
409 Conflict could be an acceptable solution.
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
The doc continues with an example:
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.
I believe this is what the OP wanted: an error code suitable for when the data does not pass the server’s criteria.
AxiosError : Request failed with status code 400 (in React JS)
I am trying to post comments using axios. When I submit my datas entered in the form, I see this error in the console :
Here is my code :
Have a look on my server :
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You’re not sending anything to your API. CommentsAPI.create(YOUR COMMENT HERE)
Also, in your server you will need to return helpful error message. Like ‘Hey, there is no message, please send a message in the payload’. That will help you understand better what’s going on.
For anyone else, who is facing the same issue, try changing your get http request to post, if you are sending data from body that has a list. Hope this helps.
If you receive a 400 (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_client_errors), it means that the sever received your request but the content was not valid. Read the documentation of the API to be sure you send the correct payload.
By default, if Axios receives something other than a 2xx, it will throw an exception
Коды ответов протокола HTTP
Access_log содержит следующую информацию:
Код состояния HTTP — это трехзначный код ответа на HTTP-запрос. Он предназначен для использования автоматами, поясняющая фраза после него предназначена для пользователей.
Первая цифра кода состояния определяет класс ответа:
1xx: Информационные коды — запрос получен, продолжается обработка.
2xx: Успешные коды — запрос был успешно получен, понят и выполнен.
3xx: Коды перенаправления — для выполнения запроса должны быть предприняты дальнейшие действия агента пользователя (программы, принимающей ответ на запрос).
4xx: Коды ошибок клиента — запрос имеет плохой синтаксис или не может быть выполнен. Также указывает, является ли ситуация временной или постоянной.
5xx: Коды ошибок сервера — сервер не в состоянии выполнить допустимый запрос или выполнил его с ошибкой.
Просмотр кода ответа протокола HTTP
Один из самых простых способов увидеть коды ответа — зайти в инструменты разработчика в браузере. Например, для браузеров google chrome и mozilla firefox достаточно:
На скриншоте показаны инструменты разработчика google chrome, коды ответа есть в колонке Status.
Наиболее распространённые коды ответов протокола HTTP
Список прочих кодов ответов протокола HTTP
405 Method Not Allowed (Метод не дозволен)- метод, определенный в строке запроса (Request-Line) не дозволено применять для ресурса, идентифицированного запрашиваемым URI (Request-URI).
410 Gone (Удален)- запрошенный ресурс больше не доступен на сервере, и нет никакого адреса для перенаправления запроса.
400 против 422 ответа на POST данных
Я пытаюсь выяснить, какой правильный код состояния должен возвращаться в различных сценариях с помощью API-интерфейса типа REST, над которым я работаю. Допустим, у меня есть конечная точка, которая позволяет делать покупки POST в формате JSON. Это выглядит так:
Что я должен вернуть, если клиент отправляет мне «sales_tax» (вместо ожидаемого «налога»). В настоящее время я возвращаю 400. Но я начал сомневаться в этом. Должен ли я действительно возвращать 422? Я имею в виду, что это JSON (который поддерживается) и это действительный JSON, он просто не содержит всех обязательных полей.
400 Bad Request теперь может показаться лучшим кодом состояния HTTP / 1.1 для вашего варианта использования.
Во время вашего вопроса (и моего первоначального ответа) RFC 7231 не был чем-то особенным; в этот момент я возразил, 400 Bad Request потому что RFC 2616 сказал (с акцентом мой):
и запрос, который вы описываете, является синтаксически допустимым JSON, заключенным в синтаксически допустимый HTTP, и, следовательно, у сервера нет проблем с синтаксисом запроса.
Код состояния 400 (неверный запрос) указывает на то, что сервер не может или не будет обрабатывать запрос из-за чего-то, что воспринимается как ошибка клиента (например, синтаксис искаженного запроса, кадрирование неверного сообщения запроса или обманчивая маршрутизация запроса).
Однако до этой переписки (или если вы хотите поспорить о том, что RFC 7231 является только предлагаемым стандартом прямо сейчас), 422 Unprocessable Entity не кажется неправильным код состояния HTTP для вашего варианта использования, потому что во введении к RFC 4918 говорится:
Хотя коды состояния, предоставляемые HTTP / 1.1, достаточны для описания большинства состояний ошибок, с которыми сталкиваются методы WebDAV, есть некоторые ошибки, которые не попадают аккуратно в существующие категории. Эта спецификация определяет дополнительные коды состояния, разработанные для методов WebDAV (Раздел 11)
Код состояния 422 (Unprocessable Entity) означает, что сервер понимает тип содержимого объекта запроса (следовательно, код состояния 415 (Unsupported Media Type) является неподходящим), и синтаксис объекта запроса является правильным (таким образом, 400 (неверный запрос) ) код состояния не подходит), но не удалось обработать содержащиеся в нем инструкции.
(Обратите внимание на ссылку на синтаксис; я подозреваю, что 7231 частично устарел и 4918)
Это звучит точно так же, как ваша ситуация, но на случай, если возникли какие-либо сомнения, он говорит:
Например, это условие ошибки может возникнуть, если тело запроса XML содержит правильно сформированные (то есть синтаксически правильные), но семантически ошибочные инструкции XML.
(Замените «XML» на «JSON», и я думаю, что мы можем согласиться, что это ваша ситуация)
Теперь некоторые будут возражать, что RFC 4918 относится к «HTTP-расширениям для Web-распределенной авторизации и управления версиями (WebDAV)» и что вы (предположительно) ничего не делаете с WebDAV, поэтому не должны использовать его.
Учитывая выбор между использованием кода ошибки в исходном стандарте, который явно не охватывает ситуацию, и кодом из расширения, которое точно описывает ситуацию, я бы выбрал последний.
Я предполагаю, что для клиента или сервера HTTP вполне разумно использовать любой код состояния из этого реестра, если они делают это правильно.
Сервер не может понять запрос из-за неправильного синтаксиса. Клиент НЕ ДОЛЖЕН повторять запрос без изменений.
Это условие ошибки может возникнуть, если тело XML-запроса содержит правильно сформированные (т. Е. Синтаксически правильные), но семантически ошибочные инструкции XML.
Чтобы сохранить единый интерфейс, вы должны использовать 422 только в случае ответов XML, а также поддерживать все коды состояния, определенные расширением Webdav, а не только 422.
Смотрите также сообщение Марка Ноттингема о кодах статуса:
Чтобы отразить статус на 2015 год:
Поведенческие и ответные коды 400 и 422 будут одинаково восприниматься клиентами и посредниками, так что это на самом деле не имеет конкретного значения, которое вы используете.
Однако я ожидаю увидеть 400 используемых в настоящее время более широко, и, кроме того, пояснения, которые предоставляет спецификация HTTPbis, делают его более подходящим из двух кодов состояния:
Пример использования GitHub API
Существует три возможных типа ошибок клиента при вызовах API, которые получают тела запросов:
Отправка неверного JSON приведет к ответу 400 Bad Request.
Отправка неправильного типа значений JSON приведет к ответу 400 Bad Request.
Отправка неверных полей приведет к ответу 422 Unprocessable Entity.
Правильного ответа нет, поскольку это зависит от того, какое определение «синтаксис» используется для вашего запроса. Самое главное, что вы:
Прежде чем все обрушатся на меня, сказав, что здесь нет правильного или неправильного ответа, позвольте мне немного объяснить, как я пришел к выводу.
В этом конкретном примере вопрос OP касается запроса JSON, который содержит ключ, отличный от ожидаемого. Теперь полученное имя ключа очень похоже, с точки зрения естественного языка, на ожидаемый ключ, но оно строго отличается и, следовательно, не распознается (обычно) машиной как эквивалентное.
Объяснение 422 необработанного объекта Обновлено: 6 марта 2017 г.
Что такое 422 необработанный объект?
Код состояния 422 возникает, когда запрос правильно сформирован, однако из-за семантических ошибок он не может быть обработан. Этот статус HTTP был введен в RFC 4918 и более конкретно ориентирован на расширения HTTP для Web Distributed Authoring and Versioning (WebDAV).
Существует некоторое противоречие относительно того, должны ли разработчики возвращать клиентам ошибку 400 против 422 (подробнее о различиях между обоими статусами ниже). Однако в большинстве случаев считается, что статус 422 следует возвращать только в том случае, если вы поддерживаете возможности WebDAV.
Дословное определение кода состояния 422, взятого из раздела 11.2 в RFC 4918, можно прочитать ниже.
Код состояния 422 (Unprocessable Entity) означает, что сервер понимает тип содержимого объекта запроса (следовательно, код состояния 415 (Unsupported Media Type) является неподходящим), и синтаксис объекта запроса является правильным (таким образом, 400 (неверный запрос) ) код состояния не подходит), но не удалось обработать содержащиеся в нем инструкции.
Определение продолжает говорить:
Например, это условие ошибки может возникнуть, если тело запроса XML содержит правильно сформированные (то есть синтаксически правильные), но семантически ошибочные инструкции XML.
400 против 422 кодов состояния
Ошибочные ошибки запроса используют код состояния 400 и должны быть возвращены клиенту, если синтаксис запроса неверен, содержит недопустимое обрамление сообщения запроса или имеет обманчивую маршрутизацию запроса. Этот код состояния может показаться очень похожим на состояние необработанного объекта 422, однако одна небольшая часть информации, которая их отличает, заключается в том, что синтаксис объекта запроса для ошибки 422 является правильным, тогда как синтаксис запроса, который генерирует 400 ошибка неверна
Использование статуса 422 должно быть зарезервировано только для очень конкретных случаев использования. В большинстве других случаев, когда произошла ошибка клиента из-за неправильного синтаксиса, следует использовать статус 400 Bad Request.
Идеальный сценарий для 422:
В идеальном мире 422 является предпочтительным и в целом приемлемым для отправки в качестве ответа, если сервер понимает тип содержимого объекта запроса, и синтаксис объекта запроса является правильным, но не смог обработать данные, поскольку они семантически ошибочны.
Ситуации 400 на 422:
В корпоративной архитектуре сервисы развертываются в основном на сервисных уровнях, таких как SOA, IDM и т. Д. Они обычно обслуживают несколько клиентов, начиная от очень старого собственного клиента и заканчивая новейшими клиентами HTTP. Если один из клиентов не обрабатывает HTTP 422, возможны варианты, когда клиент просит обновить или изменить код ответа на HTTP 400 для всех. По моему опыту, это очень редко в наши дни, но все еще возможность. Поэтому перед принятием решения о кодах ответа HTTP всегда требуется тщательное изучение вашей архитектуры.
Чтобы справиться с подобной ситуацией, сервисные уровни обычно используют versioning или устанавливают configuration флаг для клиентов строгого соответствия HTTP для отправки 400 и отправки 422 для остальных из них. Таким образом, они обеспечивают поддержку обратной совместимости для существующих потребителей, но в то же время предоставляют возможность новым клиентам использовать HTTP 422.
Последнее обновление RFC7321 гласит:
Во-первых, это очень хороший вопрос.
например, заголовок авторизации или заголовок типа контента. Который абсолютно необходим серверу для понимания запроса. Это может отличаться от сервера к серверу.
Это менее серьезно, чем 400. Запрос достиг сервера. Сервер подтвердил, что запрос имеет правильную базовую структуру. Но информация в теле запроса не может быть проанализирована или понята.
Вот статья, в которой перечислены коды состояния и их использование в REST API. https://metamug.com/article/status-codes-for-rest-api.php
На самом деле вы должны вернуть «200 OK» и в теле ответа включить сообщение о том, что произошло с опубликованными данными. Тогда ваше приложение должно понять сообщение.
Позвольте мне привести не виртуальный пример. Допустим, вы влюбились в девушку, и она любит вас обратно, но ее семья переезжает в совершенно другую страну. Она дает вам свой новый почтовый адрес. Естественно, вы решили отправить ей любовное письмо. Итак, вы пишете свое письмо, кладете его в конверт, пишете ее адрес на конверте, ставите на нем штамп и отправляете его. Теперь давайте рассмотрим эти сценарии
Короче говоря, возвращение «200 OK» не означает, что у серверного приложения есть хорошие новости для вас. Это только означает, что у него есть новости.
PS: код состояния 422 имеет значение только в контексте WebDAV. Если вы не работаете с WebDAV, то 422 имеет то же самое стандартное значение, что и любой другой нестандартный код = которого нет.
400 BAD request HTTP error code meaning?
I have a JSON request which I’m posting to a HTTP URL.
Should this be treated as 400 where requestedResource field exists but «Roman» is an invalid value for this field?
Should this be treated as 400 where «blah» field doesn’t exist at all?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn’t follow the rules.
In the case of a REST API with a JSON payload, 400’s are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation—either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
Rules are as following:
So in your case I’d returned 400 error and something like this if «Roman» is obtained from user input and client must have specific reaction:
or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:
Error 400 Bad request when I use PHP CURL
When I CURL in PHP. With appropriate headers and fields but It will give me error Error 400 Bad request. Why this error becomes?
Header Request
CURL Code
If you want any further data please comment I will explain in detail.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 400 response means that the HTTP server that the request went to has said that the request is invalid.
Who knows! Maybe the URL you sent in the request has malformed arguments (in the query string) or maybe it requires arguments that you didn’t supply. Or maybe the problem is the other headers.
Or maybe it just doesn’t like you.
I suggest that you compare the request you are sending with either the web site’s API documentation or a request sent by a (real) browser. And if that fails, ask the folks who look after the web server you are sending the requests to.
What is HTTP error 400 and how do you fix it?
Tips and tricks to diagnose and debug a 400 Bad Request error
Client-server interactions tend to happen incessantly and smoothly. Despite this, a 400 Bad Request error usually indicates a request that hasn’t been met successfully, or could mean that the remote server you sent your request to could not understand the request as it became corrupted.
Malformed requests can result in error messages as servers respond to requests in a specific and often fixed format. To add to the confusion, sometimes the server itself may cause the error but only in select few instances. Depending on the browser you’re using, HTTP errors may also appear differently.
When it comes to Firefox and Safari, they usually display a blank page with no status code. Chrome, on the other hand, shows a generic “This page isn’t working” message along with an error code.
Here you can find a list of the most common error messages that users have reported while facing a 400 Bad Request error:
Website owners may also opt to customize their HTTP Error 400 page to ensure reliable hosting services. An example of this is when web servers run Microsoft Internet Information Services (IIS) they show a more specific variant of the error such as “400.3: Invalid If Header”, “400.2: Invalid Depth Header”, “400.1: Invalid Destination Header”, and more.
A number of scenarios can lead to a 400 Bad Request error, although it may not be immediately apparent. Find out about the most common causes of the error and how to fix them below.
HTTP error 400 causes
There’s a variety of issues that can lead to a 400 Bad Request error. Here, we’ll go over five common issues.
1. Bad URL Syntax
A 400 Bad Request error is usually a client-side error. A good case in point is a URL string syntax error. Incorrectly typed URLs, or URLs that contain backslashes and other invalid characters can garble a request.
For example, the following URL will send you to a valid page.
Access the same URL with an extra “%” in it, and your browser will throw a 400 Bad Request error.
2. Invalid Cookies
Cookies store information about the websites you visit and may also store authentication data to speed up log in. If you can’t log into a website you previously visited, it means the cookie containing your log in data is no longer valid. This results in a 400 Bad Request error.
3. Incorrect file size
You may be trying to upload a file that’s too large to a website. The server will fail to fulfill your request and respond with a 400 error message in such a case.
Keep in mind, the hosting provider sets the maximum upload size limit at the server level. For example, the maximum file size limit for WordPress ranges from 4MB to 128MB.
4. Unsynchronized DNS Cache
Browsers read domain names as IP addresses, which are stored locally in the Domain Name System (DNS) cache to improve the browsing experience. A 400 Bad Request error can occur when the DNS data stored locally is out of sync with a website’s registered DNS information during a future interaction.
5. Server error
Servers can cause errors too. To check if there’s an issue with the server, try loading a website from a different browser and device. If the website fails to open in Edge, Chrome, Firefox, or IE, it’s likely a server-side problem.
How to fix a 400 Bad Request?
It’s hard not to be unfazed by an HTTP error that tells you little about the problem. That said, fixing a 400 Bad Request error takes just a few steps. We’ve put together a few useful tips below to help you find your way out.
1. Recheck the URL
Since a malformed URL is the most common cause of the 400 Bad Request error, make sure there are no typing or syntax errors in your URL. Alternatively, for long URLs, consider using an online URL encoder, which automatically detects non-ASCII characters or invalid characters in a URL, saving you time and effort.
2. Check your internet connection
If you keep seeing a 400 Bad Request on nearly every website you visit, check your internet connection or consult your internet service provider to rule out a poor connection.
3. Clear browser cookies
A website may fail to comply with your request due to old or corrupt cookies. As a quick fix, consider clearing your browser cache and cookies. Repeat this exercise from time to time to avoid running into a 400 Bad Request error.
4. Clear DNS Cache
This works similar to clearing browser cookies and cache, except that it’s locally stored in your computer and may contain outdated information that doesn’t sync with the current webpage. You can clear old DNS information and records from your system within the Command Prompt in Windows and Mac.
5. Compress the file
If you run into an HTTP Error 400 right after uploading a file, try uploading a smaller file. If that works, you may conclude that the initial file exceeded the server limit. The best workaround for uploading a large file is to compress it. Most websites permit zip files that fall under the maximum upload size.
6. Deactivate browser extensions
While this isn’t a common solution for a 400 Bad Request error, some browser extensions may interfere with cookies. Temporarily disabling them might resolve the problem.
7. Restart your system
If you’ve attempted all of the above fixes and the HTTP Error 400 still persists, you might want to try the good old reboot. Although often ridiculed, turning a device off and on again is surprisingly efficient in resolving an array of issues. With the HTTP Error 400, you will want to not only restart your computer but any attached peripherals – especially routers – as well.
The top three IT pains of the new reality and how to solve them
Driving more resiliency with unified operations and service management
Free download
However, if this magic fix fails is as inefficient in solving the error as the previous six methods, it might not have anything to do with you nor your devices. In some instances, an HTTP Error 400 is actually caused by a server-end issue, which in turn can be anything from data centre power cuts to an overheated or excessively humid server room environment. In short, there is little to nothing that you can do to fix a server-end issue, and there are likely multiple people working to resolve it for you. In most cases, however, a client-side HTTP error status code starts with 4, while a server-side HTTP status begins with 5.
Nevertheless, reporting the problem might bring some solace, and could help provide a better estimate of how many users are affected. This can be done by filing a report directly to the administrator of the page, or simply logging it on a monitoring site such as Down Detector.
At the end of the day, the HTTP Error 400 is very much like other HTTP errors in the way that its causes are often mysterious as well as baffling. In many cases, they can be traced back to a rather uncomplicated issue, such as expired browser files and cookies, wrongly inserted URLs, or even an incorrect file size.
Going paperless in 90 days
The three steps to quick and effective digitisation
Free Download
Navigating your hybrid cloud vision
Ensure business continuity and lower IT acquisition costs with on-premises private cloud
Free Download
Successful enterprise application modernisation requires hybrid cloud infrastructure
Optimise business outcomes with a secure and reliable modern infrastructure
Free Download
Learn how you can get an over 200% ROI with Workplace
How Workplace can help your frontline workers
Free Download
Источники:
- http://stackoverflow.com/questions/57180480/error-request-failed-with-status-code-400-differences-between-sending-in-postm
- http://stackoverflow.com/questions/72307388/axioserror-request-failed-with-status-code-400-in-react-js
- http://stackoverflow.com/questions/65511861/request-failed-with-status-code-400-with-axios
- http://stackoverflow.com/questions/10847224/rest-when-to-use-400-bad-request
- http://docs.microsoft.com/en-us/troubleshoot/developer/webapps/iis/www-administration-management/http-bad-request-response-kerberos
- http://stackoverflow.com/questions/44731340/getting-400-error-bad-request-using-axios
- http://stackoverflow.com/questions/41712562/request-failed-with-status-code-400?lq=1
- http://stackoverflow.com/questions/51990143/400-vs-422-for-client-error-request
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning/19671511
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning?lq=1
- http://stackoverflow.com/questions/41712562/request-failed-with-status-code-400/41713384
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning),
- http://stackoverflow.com/questions/42143115/which-status-code-is-correct-404-or-400-and-when-to-use-either-of-these
- http://helpmyos.ru/internet/ispravlenie-oshibki-400-bad-request/
- http://stackoverflow.com/questions/17792931/ssrs-error-message-the-request-failed-with-http-status-400-bad-request
- http://stackoverflow.com/questions/48499693/cors-errors-only-with-400-bad-request-react-fetch-request
- http://stackoverflow.com/questions/66097190/error-request-failed-with-status-code-400-in-react-native-with-axios
- http://developer.mozilla.org/en-US/docs/Web/HTTP/Status?retiredLocale=bg
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning/24610322
- http://myroad.club/kak-ispravit-oshibku-400-bad-ili-invalid-request-http-webnots/
- http://stackoverflow.com/questions/35724189/http-header-400-bad-request-response
- http://stackoverflow.com/questions/41712562/request-failed-with-status-code-400/50413010
- http://stackoverflow.com/questions/29912305/response-code-400-or-403-for-post-restful-apis
- http://stackoverflow.com/questions/57180480/error-request-failed-with-status-code-400-differences-between-sending-in-postm?rq=1
- http://stackoverflow.com/questions/51990143/400-vs-422-for-client-error-request?rq=1
- http://techblog.sdstudio.top/kak-ispravit-oshibku-400-bad-ili-invalid-request-http/
- http://www.javatpoint.com/status-code-400
- http://social.msdn.microsoft.com/Forums/en-US/ecd56efb-7615-440d-8077-5aaedc66ca57/request-failed-with-status-code-400-and-status-text-bad-request-using-iis?forum=lightswitch
- http://docs.commercetools.com/api/errors
- http://stackoverflow.com/questions/69260984/error-request-failed-with-status-code-400-when-expo-buidl
- http://dev.to/t410/expo-cli-request-failed-with-status-code-404-2pjg
- http://stackoverflow.com/questions/4781187/http-400-bad-request-for-logical-error-not-malformed-request-syntax
- http://pomogaemkompu.temaretik.com/1386851685667178766/kak-ispravit-oshibku-400—podrobnaya-instruktsiya-po-resheniyu-problemy/
- http://kinsta.com/blog/http-status-codes/
- http://stackoverflow.com/questions/3050518/what-http-status-response-code-should-i-use-if-the-request-is-missing-a-required
- http://stackoverflow.com/questions/702079/why-does-my-httpwebrequest-return-400-bad-request
- http://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm
- http://developer.mozilla.org/en-US/docs/Web/HTTP/Status?retiredLocale=uk
- http://stackoverflow.com/questions/63247941/react-js-sending-json-to-spring-boot-request-failed-with-status-code-400
- http://stackoverflow.com/questions/48489285/postman-error-400-bad-request
- http://stackoverflow.com/questions/70399744/i-get-a-400-status-code-error-from-a-github-pages-deployment
- http://docs.microsoft.com/en-us/exchange/troubleshoot/client-connectivity/400-bad-request
- http://stackoverflow.com/questions/27467930/400-bad-request-the-ssl-certificate-error
- http://stackoverflow.com/questions/16017081/getting-400-bad-request-error-in-jquery-ajax-post
- http://club.cnews.ru/blogs/entry/chto_oznachayut_oshibki_400_403_404_500_502_503_i_kak_ih_ispravit_
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning/39644190
- http://stackoverflow.com/questions/9985327/asp-net-web-api-httpresponseexception-400-bad-request-hijacked-by-iis
- http://sm-stackoverflow.azurefd.net/questions/65511861/request-failed-with-status-code-400-with-axios/65512155
- http://pr-cy.ru/news/p/7246-chto-oznachaet-kod-otveta-servera
- http://stackoverflow.com/questions/30522411/400-bad-requests
- http://adminu.ru/2012/01/kody-statusov-hhtp-4xx-oshibki-klienta/
- http://stackoverflow.com/questions/56403926/400bad-request-status-code-when-making-request-with-axios-in-reactjs
- http://www.askapache.com/htaccess/apache-status-code-headers-errordocument/
- http://www.syl.ru/article/302449/oshibka-bad-request—chto-eto-i-kak-ee-ustranit
- http://stackoverflow.com/questions/62441209/react-native-to-django-using-axios-error-request-failed-with-status-code-400
- http://stackoverflow.com/questions/1364527/http-status-code-for-bad-data
- http://blog.runscope.com/posts/how-to-debug-common-api-errors
- http://web-shpargalka.ru/http-error-400-chto-za-oshibka.php
- http://stackoverflow.com/questions/7939137/what-http-status-code-should-be-used-for-wrong-input
- http://stackoverflow.com/questions/72307388/axioserror-request-failed-with-status-code-400-in-react-js/72325861
- http://help.sweb.ru/entry/205/
- http://qastack.ru/programming/16133923/400-vs-422-response-to-post-of-data
- http://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning?
- http://stackoverflow.com/questions/24569281/error-400-bad-request-when-i-use-php-curl
- http://www.itpro.com/infrastructure/network-internet/359323/what-is-http-error-400-and-how-do-you-fix-it