admin管理员组文章数量:1304149
Building on this answer, the WP_REST_Response()
object returned by the callback function of my custom route is not the object I'm asking it to return. My object has a "status" of 304 and a "message" field, the object returned has a "status" of 200 and no "message" field. Why?
Below I simplified sendContactMail()
's code and created an error response. None of this ends up showing up in the console (see bottom of my question):
function sendContactMail(WP_REST_Request $request) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
return new WP_REST_Response($response);
}
add_action('rest_api_init', function() {
register_rest_route('contact/v1', 'send', array(
'methods' => 'POST',
'callback' => 'sendContactMail',
'permission_callback' => '__return_true',
'args' => array(
'contact_name' => array(
'required' => true,
'validate_callback' => function ($value) {
return preg_match('/[a-z0-9]{2,}/i', $value) ? true :
new WP_Error('invalid_contact_name', 'Your custom error.');
},
'sanitize_callback' => 'sanitize_text_field',
),
'contact_email' => array(
'required' => true,
'validate_callback' => 'is_email',
'sanitize_callback' => 'sanitize_email',
),
'contact_message' => array(
'required' => true,
'sanitize_callback' => 'sanitize_textarea_field',
),
),
));
});
Front-end:
fetch(`${this.baseUrl}/wp-json/contact/v1/send`, {
method: 'POST',
body: formData
})
.then((res) => {
if (res.status === 304) {
// do something
} else {
// do something different
}
})
.catch(error => {
console.log(error)
})
Console:
Building on this answer, the WP_REST_Response()
object returned by the callback function of my custom route is not the object I'm asking it to return. My object has a "status" of 304 and a "message" field, the object returned has a "status" of 200 and no "message" field. Why?
Below I simplified sendContactMail()
's code and created an error response. None of this ends up showing up in the console (see bottom of my question):
function sendContactMail(WP_REST_Request $request) {
$response = array(
'status' => 304,
'message' => 'There was an error sending the form.'
);
return new WP_REST_Response($response);
}
add_action('rest_api_init', function() {
register_rest_route('contact/v1', 'send', array(
'methods' => 'POST',
'callback' => 'sendContactMail',
'permission_callback' => '__return_true',
'args' => array(
'contact_name' => array(
'required' => true,
'validate_callback' => function ($value) {
return preg_match('/[a-z0-9]{2,}/i', $value) ? true :
new WP_Error('invalid_contact_name', 'Your custom error.');
},
'sanitize_callback' => 'sanitize_text_field',
),
'contact_email' => array(
'required' => true,
'validate_callback' => 'is_email',
'sanitize_callback' => 'sanitize_email',
),
'contact_message' => array(
'required' => true,
'sanitize_callback' => 'sanitize_textarea_field',
),
),
));
});
Front-end:
fetch(`${this.baseUrl}/wp-json/contact/v1/send`, {
method: 'POST',
body: formData
})
.then((res) => {
if (res.status === 304) {
// do something
} else {
// do something different
}
})
.catch(error => {
console.log(error)
})
Console:
Share Improve this question edited Feb 6, 2021 at 22:09 drake035 asked Feb 6, 2021 at 22:04 drake035drake035 1,2177 gold badges34 silver badges57 bronze badges1 Answer
Reset to default 4I believe WP_Rest_Response
did return the proper response based on what your endpoint callback returns, but I think you just not understanding what fetch()
returns, so please check the documentation on MDN for more details, but here's an excerpt that might help you:
The
fetch()
method takes one mandatory argument, the path to the resource you want to fetch. It returns aPromise
that resolves to theResponse
to that request, whether it is successful or not.
So referring to your screenshot, you're actually viewing the above-mentioned Response
object which includes the body, headers, URL, etc. And the response body is that body
property there (click the body: (...)
), but to get the actual JSON data in the response, you can use res.json()
:
fetch ( `${this.baseUrl}/wp-json/contact/v1/send`, {
method: 'POST',
body: formData,
} )
.then(
( res ) => {
res.json().then(
( data ) => console.log( data, res.status ),
( jsonError ) => console.log( jsonError )
);
},
( error ) => console.log( error )
);
And actually, that status
in your $response
array is part of the response body, so that $response
is actually the response body.
If you want to send a custom HTTP status code, you can use the second parameter for WP_HTTP_Response::__construct()
which is inherited by the WP_REST_Response
class which extends WP_HTTP_Response
.
But, are you sure you want to use the 304 ("Not Modified") status? Because that would return no response body.. So you should instead use 400 ("Bad Request") to indicate an error in the request.
function sendContactMail( WP_REST_Request $request ) {
// dummy param, used for emitting an error, if requested
$ok = empty( $request['is_error'] );
// Send the response with custom HTTP status code.
if ( $ok ) {
return new WP_REST_Response( array( 'message' => 'Form sent!' ), 200 );
} else {
return new WP_REST_Response( array( 'message' => 'Something wrong..' ), 400 );
}
}
Or you could also just return a WP_Error
instance and the status code will default to 400:
function sendContactMail( WP_REST_Request $request ) {
// dummy param, used for emitting an error, if requested
$ok = empty( $request['is_error'] );
// Use the default HTTP status codes.
if ( $ok ) {
return new WP_REST_Response( array( 'message' => 'Form sent!' ) );
} else {
return new WP_Error( 'foo_code', 'Something wrong..' );
}
}
本文标签: rest apiWPRESTResponse() doesn39t seem to return the expected object
版权声明:本文标题:rest api - WP_REST_Response() doesn't seem to return the expected object 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741769063a2396640.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论