wordpress - 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}}
解决方案
你通过 注册了一个GET
路由'methods' => WP_REST_Server::READABLE
,但是POST
在 curl 中发送了一个请求。您需要统一请求方法,无论是GET还是POST。
推荐阅读
- c# - 解构器歧义的位置模式匹配
- javascript - 在 JavaScript 中,当必须缩小文件时省略分号是否安全?
- javascript - 一些图像即使存在也没有加载到反应应用程序中
- c++ - Eigen:在子矩阵上重复操作的有效方法
- firebase - Firebase 按存在的孩子排序
- amazon-web-services - Terraform 分离并重新附加 ebs 卷
- swift - 您可以强制字典返回非可选或断言吗?
- sql-server - 透视 SQL 服务器结果
- java - 来自系统属性的 spring.datasource.password 不起作用
- c - 为什么可重入随机生成器 rand_r() 被认为是弱的?