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
This commit is contained in:
K. Adam White 2019-08-15 19:55:13 +00:00
parent 22480c035b
commit 80e44e49e2
2 changed files with 47 additions and 0 deletions

View File

@ -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();

View File

@ -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!' );