introduction
A new interface in the request background suddenly reports an error 400 (Bad Request), but it can be used normally in YAPI. What is the reason?
After comparing with other similar interfaces, it is found that the problem is Content-Type
above. The normal interface is used application/x-www-form-urlencoded; charset=utf-8"
, and the request body is in the form of Form Data; while the wrong interface is used application/json;charset=UTF-8
, the request body is: Request Payload
.
What is the difference between x-www-form-ulencoded and json?
To solve this problem, you must first know the difference between the two. Before you figure it out, you need to know Content-Type
what it is and what types it has.
Content-Type
The header is actually to tell the type of data carried by the receiving party, just like the file suffix used in our computer, so that we know what type to use to open it. The common data types are:
at the beginning, it is text/plain;charset=UTF-8
a type, which is in the form of a string, and it doesn’t matter what is passed in it, such as: ; “Hello World”
Later, a form type appeared application/x-www-form-urlencoded
, and this form mainly exists in the form of key-value. Key-value pairs are separated by &, such as: username=admin & password=123456
; With the development of the Internet, traditional forms can no longer meet the needs, and various multimedia formats have emerged. Now we use the JSON format most: , that is, the application/json
transmission content is all JSON-formatted object, such as: {“username”: admin , “password”: 123456}
.
in conclusion
When Content-Type
it is:, application/x-www-form-urlencoded
the browser displays it as FormData
When it is Content-Type
:, application/json
the browser displays it as requestPayload
In fact, no matter which type is used, as long as the front and back ends are agreed, there will be no problem. I have a problem here because the background interface uses the form format to accept. To solve this problem, either change the background acceptance format to accept the JSON object format to keep it consistent with the front-end, or modify the front-end to the form form Content-Type
.
solve
I modify the front-end code here, and Content-Type
customize it as: application/x-www-form-urlencoded
the request is successful, I hope it can help your problem!