WordPress API在触发时返回false

mhd8tkvw  于 2023-08-03  发布在  WordPress
关注(0)|答案(1)|浏览(103)


的数据
下面是我的代码:

const userAction = async () => {
        const response = await fetch('https://rajivrajput.com/wp-json/mmw/v1/testing', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const myJson = await response.json(); //extract JSON from the http response
        console.log(myJson);
        // do something with myJson
        document.getElementById("div").innerHTML = myJson;
    }

字符串
这是我的function.php文件...

$user_id = ""; //<- add this

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    $GLOBALS['user_id'] = get_current_user_id(); //<- add this

    // route url: domain.com/wp-json/mmw/v1/testing
    register_rest_route( 'mmw/v1', 'testing', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}
//Customize the callback to your liking
function get_custom_users_data(){
     return $user_info =  get_user_by( 'id', $GLOBALS['user_id'] ); //<- add this
}


当我通过浏览器访问这个https://agriculturecoaching.in/wp-json/mmw/v1/testing时,它提供了一个JSON,但当我通过代码访问时,它是false。?

ctehm74n

ctehm74n1#

当你从js代码发送请求时,你没有提供API调用X-WP-NONCE头,没有nonce wp不能链接到WordPress生态系统中的用户,请看看文档https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

相关问题