我有一个简单的端点。它的GET,我给它传递一个ID参数,它使用这个ID进行curl调用。然后,端点使用json\\U编码的几条信息进行响应。
问题是该端点一直在缓存其结果。我如何防止这种情况发生?
夫妻注:
没有安装缓存插件,WP config没有注意缓存。端点代码非常简单:
// Get Number of people in line
add_action( \'rest_api_init\', function () {
register_rest_route( \'cc/v1\', \'/in_line/(?P<id>\\d+)\', array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => \'in_line\',
\'args\' => [
\'id\'
],
) );
} );
function in_line($data) {
//Do a bunch of Curl stuff
$response[\'queue\'] = $number;
$response[\'queueID\'] = $data[\'id\'];
return json_encode($response);
}
我通过jQuery ajax调用端点。
SO网友:Mostafa Soufi
您应该从创建新实例WP_REST_Response
设置缓存控制值。
<?php
// Get Number of people in line
add_action( \'rest_api_init\', function () {
register_rest_route( \'cc/v1\', \'/in_line/(?P<id>\\d+)\', array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => \'in_line\',
\'args\' => [
\'id\'
],
) );
} );
function in_line($data) {
//Do a bunch of Curl stuff
$response[\'queue\'] = $number;
$response[\'queueID\'] = $data[\'id\'];
$result = new WP_REST_Response($response, 200);
// Set headers.
$result->set_headers(array(\'Cache-Control\' => \'no-cache\'));
return $result;
}
SO网友:Jewel
根据@fränk的评论,正确且更优雅的方式如下:
<?php
// Get Number of people in line
add_action( \'rest_api_init\', function () {
register_rest_route( \'cc/v1\', \'/in_line/(?P<id>\\d+)\', array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => \'in_line\',
\'args\' => [
\'id\'
],
) );
} );
function in_line($data) {
//Do a bunch of Curl stuff
$response[\'queue\'] = $number;
$response[\'queueID\'] = $data[\'id\'];
nocache_headers();
$result = new WP_REST_Response($response, 200);
return $result;
}