From 80e44e49e2733a87681181a19aa63bb01f5710b9 Mon Sep 17 00:00:00 2001 From: "K. Adam White" Date: Thu, 15 Aug 2019 19:55:13 +0000 Subject: [PATCH] REST API: Do not send response body if status is 204 or body is null. Status code 204 should indicate no response body is sent. Previously, a "null" string was sent, which MacOS Safari would try to parse as JSON and thereby fail to complete the request. Props TimothyBlynJacobs, andizer, matthias.thiel. Fixes #43691. git-svn-id: https://develop.svn.wordpress.org/trunk@45809 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/class-wp-rest-server.php | 5 +++ tests/phpunit/tests/rest-api/rest-server.php | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php index 68be073eef..7f158959e9 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -405,6 +405,11 @@ class WP_REST_Server { */ $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request ); + // The 204 response shouldn't have a body. + if ( 204 === $code || null === $result ) { + return null; + } + $result = wp_json_encode( $result ); $json_error_message = $this->get_json_last_error(); diff --git a/tests/phpunit/tests/rest-api/rest-server.php b/tests/phpunit/tests/rest-api/rest-server.php index 8c514e9e66..efb656ed4e 100644 --- a/tests/phpunit/tests/rest-api/rest-server.php +++ b/tests/phpunit/tests/rest-api/rest-server.php @@ -1144,6 +1144,48 @@ class Tests_REST_Server extends WP_Test_REST_TestCase { $this->assertEquals( 200, $response->get_status() ); } + /** + * @ticket 43691 + */ + public function test_does_not_echo_body_for_null_responses() { + register_rest_route( + 'test-ns', + '/test', + array( + 'methods' => array( 'GET' ), + 'callback' => function () { + return new WP_REST_Response(); + }, + ) + ); + + $result = rest_get_server()->serve_request( '/test-ns/test' ); + + $this->assertNull( $result ); + $this->assertEquals( '', rest_get_server()->sent_body ); + } + + /** + * @ticket 43691 + */ + public function test_does_not_echo_body_for_responses_with_204_status() { + register_rest_route( + 'test-ns', + '/test', + array( + 'methods' => array( 'GET' ), + 'callback' => function () { + return new WP_REST_Response( 'data', 204 ); + }, + ) + ); + + $result = rest_get_server()->serve_request( '/test-ns/test' ); + + $this->assertNull( $result ); + $this->assertEquals( '', rest_get_server()->sent_body ); + } + public function _validate_as_integer_123( $value, $request, $key ) { if ( ! is_int( $value ) ) { return new WP_Error( 'some-error', 'This is not valid!' );