首页 > 解决方案 > Wordpress rest API 在浏览器上工作,但不适用于 curl

问题描述

我编写了这段代码来注册 REST 路由,它在浏览器中运行良好,但不适用于 CURL

function my_func()
{
    return new WP_REST_Response('ok');
}

function init_my_func(){
    $namespace = 'test/v1';
    $route     = 'fire';

    register_rest_route($namespace, $route, array(
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => 'my_func',
        'args' => array(),
        'permission_callback' => function () {
        return true;
        }
    ));
}

add_action('rest_api_init', 'init_my_func');

卷曲代码:

$params = array();
$params['arg1'] = 'value1';
$json = json_encode($params);

$url = "http://example.com/wp-json/test/v1/fire";
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "Content-Type: application/json;"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

响应:

{\"code\":\"rest_no_route\",\"message\":\"No route was found matching the URL and request method.\",\"data\":{\"status\":404}}

标签: wordpress

解决方案


你通过 注册了一个GET路由'methods' => WP_REST_Server::READABLE,但是POST在 curl 中发送了一个请求。您需要统一请求方法,无论是GET还是POST。


推荐阅读