[英]404 on http://localhost/wp-json/wp/v2/posts in wordpress using REST API V2
[英]Wordpress wp rest api v2 error 400 (Bad Request)“ Object {code: ”rest_invalid_param“, message: ”Invalid parameter(s): id", data: Object}
在對使用“ wp rest api v2”的WordPress應用程序的本地主機請求中,按預期工作沒有問題。 這是我的本地主持人發布請求的示例:
POST“ http://127.0.0.1/plugin名稱空間/ plugin-name / wp-json / plugin名稱空間/ api URL的其余部分”
但是在我的托管站點上,該請求返回了一個錯誤,與我的托管站點類似的請求:
POST“ http://my-domain.com/plugin-name/wp-json/plugin名稱空間/ api URL的其余部分”
然后進入chrome控制台“ 400(錯誤請求)”對象{代碼:“ rest_invalid_param”,消息:“無效參數:id”,數據:對象}
還要注意,兩個請求中的有效載荷是相同的:
$ http.post(url,{id:1,shortMessage:“ abc”},{headers:{'X-WP-Nonce':“我的現時值”}}); //我正在使用angular $ http發出發布請求
我寫了上面的網址。
在我的插件php代碼中,我寫道:
function myplugin_register_endpoints(){
register_rest_route(
'plugin namespace',
'/rest of the api url',
array(
'methods' => 'POST',
'callback' => 'my_end_point',
'args' => array(
'id' => array(
'required' => true,
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param ) and ! is_null(get_post($param));//numeric post id value and there is valid post for this id
},
'sanitize_calback' => 'absint'
)
),
'permission_callback' => function (WP_REST_Request $request) {
if(!is_user_logged_in()){
return new WP_Error('login error',__('You are not logged in','blabla'));
}
return true;
}
)
);
}
add_action('rest_api_init','myplugin_register_endpoints');
function my_end_point(WP_REST_Request $request) {
global $current_user;
$current_user = wp_get_current_user();
if($my_var){
return array('message' => $message,'items' => $items,'item'=>$item);
} else {
return new WP_Error('add friend error',__('message'),$request['id']);
}
}
我需要了解為什么請求在我的托管站點上失敗。
謝謝K
我發現了我的錯誤。
就在這條線上:
返回is_numeric($ param)和! is_null(get_post($ param)); //數字發布ID值,此ID有有效的發布
我將其更改為:
返回is_numeric($ param);
發生這種情況是因為我在不修改'validate_callback'邏輯的情況下復制粘貼了register_rest_route(...){...}部分。
此“ validate_callback”中的參數是用戶ID,而不是帖子ID。 因此,檢查參數是否為發布ID(...和!is_null(get_post($ param)); ...)的部分與此端點無關。 因此,在省略此檢查之后,端點通過了“ validate_callback”並停止返回錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.