HTTP 请求体编码用 json 还是 x-www-form-urlencoded

  • application/x-www-form-urlencoded
  • application/json

axios 和 superagent 默认使用 JSON body

来自专家的建议

The Stripe API is organized around REST. Our API has predictable resource-oriented URLs, accepts form-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs

-- Stripe Docs

Creating or updating a resource involves performing an HTTP PUT or HTTP POST to a resource URI. In the PUT or POST, you represent the properties of the object you wish to update as form urlencoded key/value pairs. Don't worry, this is already the way browsers encode POSTs by default. But be sure to set the HTTP Content-Type header to "application/x-www-form-urlencoded" for your requests if you are writing your own client.

-- Twilio Docs

一些重要的事项

URL 编码数组是一个麻烦事

URL 编码

application/x-www-form-urlencoded 对 Postman 友好

HTTP GET /partners[]=Apple&partners[]=Microsoft&partners[]=Activision

等同于下列 JSON 编码格式

JSON 编码

application/json 对初学者十分友好

HTTP GET /
{"partners":["Apple","Microsoft","Activision"]}

json 会造成预检请求问题(CORS)

这是使用 application/x-www-form-urlencoded 的一个理由,因为预检请求的顺序问题总是先发送 POST 请求的预检请求
Preflight OPTIONS requests are always sent with JSON
一名开发者的回复

Ali Sherief

•[20年7月5日 • Edited on 7月5日](https://dev.to/bcanseco/request-body-encoding-json-x-www-form-urlencoded-ad9#comment-11d5i)

My app was using application/json to make requests to my API but I found a downside to it. The preflighted OPTIONS request is sent in order, but the actual POST/GET/whatever request is sent arbitrarily later after the next requests have been made. So this wrecks a stateful API if you send a POST with application/json before navigating to another page and GETing the same application/json there because the OPTIONS request for the POST will be sent first, then the next GET, then the POST itself.

For this reason I try to use application/x-www-form-urlencoded as much as possible. Preflighted requests can make race conditions.

我的应用程序使用 application/json 向我的 API 发出请求,但我发现它有一个缺点。 预检请求 OPTIONS 按顺序发送,但实际的 POST/GET/whatever 请求是在发出下一个请求后任意发送的。 因此,如果您在导航到另一个页面并在其中获取相同的 application/json 之前发送带有 application/json 的 POST,则会破坏有状态 API,因为将首先发送 POST 的 OPTIONS 请求,然后发送下一个 GET,然后发送 POST 本身。

因此,我尝试尽可能使用 application/x-www-form-urlencoded 。 预检请求可能会产生竞争条件。

posted @ 2024-01-25 21:20  我听不见  阅读(55)  评论(0编辑  收藏  举报