POST 对 WP API 的请求被解释为 GET 请求

POST requests to WP API are interpreted as GET requests

我正在尝试从 Woocommerce API 创建订单,但它没有按预期工作:请求(作为 POST 发送)正在 return 处理所有订单(例如这将是一个 GET 请求),而不是创建一个新请求。 真正奇怪的是,同样的请求在预生产服务器上运行,但在生产服务器上却没有。

这似乎是 API 的全球性问题,因为其他请求(例如从 WP API 创建 post)不工作,除了用于获取访问令牌的 POST 请求。

这是我发送的请求 POST:

curl -X POST https://www.domain.tld/wp-json/wc/v2/orders?access_token=... \
-H "Content-Type: application/json" \
-d '{
     "customer_id": "1",
     "payment_method": "app",
     "payment_method_title": "Test payment",
     "set_paid": false,
     "billing": {
         "first_name": "test",
         "last_name": "test",
         "address_1": "test",
         "address_2": "test",
         "city": "test",
         "postcode": "00000",
         "country": "FR",
         "phone": "0123456789",
         "email": "test@test.tld"
     },
     "shipping": {
         "first_name": "test",
         "last_name": "test",
         "address_1": "test",
         "address_2": "test",
         "city": "test",
         "postcode": "00000",
         "country": "FR",
         "phone": "0123456789",
         "email": "test@test.tld"
     },
     "shipping_lines": [
         {
             "method_id": "livraison_gratuite",
             "method_title": "Livraison gratuite",
             "total": 0
         }
     ],
     "line_items": [
         {
             "product_id": 302,
             "variation_id": 589,
             "quantity": 1
         },
         {
             "product_id": 798,
             "quantity": 1
         }
     ]
 }'

同样的请求在预生产服务器上运行,所以我认为问题与请求本身无关。

这是 return 我在 postman 中为生产服务器上的这个请求获取的:

我排除了所有可能的原因:

我 运行 不知道为什么会这样。任何人都知道可能导致这种情况的原因吗?

我终于知道这里发生了什么。生产服务器上有一个重定向规则,在 URL 缺失时将其添加到 URL 中。这导致请求被识别为 GET 而不是 POST(重定向 HTTP 请求时未发送 POST 数据)。

添加尾部斜杠解决了问题:

curl -X POST https://www.domain.tld/wp-json/wc/v2/orders/?access_token=...

请注意,这也可以在不使用任何此类重定向规则的预生产服务器上使用,因此请始终在 POST API 后添加斜杠requests 是个好主意,可以避免遇到此类问题。

另一种解决方案是添加此类 RewriteCond 以防止 POST 请求的重定向:

RewriteCond %{REQUEST_URI} !(/$|\.) 
RewriteCond %{THE_REQUEST} !POST
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]