简体   繁体   English

WP Rest API 自定义端点在 GET 和 POST 上返回 false

[英]WP Rest API custom endpoint returning false on GET and POST

I have a custom endpoint for User Meta that I've successfully registered to the WP REST API and created a custom endpoint for.我有一个用户元的自定义端点,我已成功注册到 WP REST API 并为其创建了一个自定义端点。 However, whenever I make GET and POST requests from my single-page app (JS framework being used is Vue), the return value is 'false.'但是,每当我从我的单页应用程序(使用的 JS 框架是 Vue)发出 GET 和 POST 请求时,返回值为“false”。

I suspect this is happening due to some authorization issues using the JWT Authorization for WP REST API plugin.我怀疑这是由于使用 JWT Authorization for WP REST API 插件的一些授权问题而发生的。

Here are my steps taken in the functions.php app:这是我在functions.php应用程序中采取的步骤:

First I register the user meta field for the REST API:首先,我为 REST API 注册用户元字段:


//register user meta to rest api 
add_action( 'rest_api_init', 'adding_user_meta_rest' );

function adding_user_meta_rest (){
    register_meta(
     'user',
     'user_likes',
     array(
         'single'       => false,
         'type'         => 'object',
         'show_in_rest' => true,
     )
 );
};

This step appears to be working fine since the field is showing up when I use the path "/wp-json/wp/v2/users/".此步骤似乎工作正常,因为当我使用路径“/wp-json/wp/v2/users/”时显示该字段。

Next step, I register the custom end point:下一步,我注册自定义端点:

add_action('rest_api_init','add_user_likes');

function add_user_likes(){
    register_rest_route(
    'v1/user_likes','/(?P<id>\d+)',[[
        'methods'=> 'GET',
        'callback'=>'get_user_likes'
    ],
    [
        'methods'=> 'POST',
        'callback'=>'post_user_likes'
    ]]);
};

And here are my callbacks:这是我的回调:

function get_user_likes(){
    $current_user_id = get_current_user_id();
    $status = $response->get_status;
    return get_user_meta($current_user_id,'user_likes');
}
function post_user_likes(WP_REST_Request $req){
    $body = $req->get_json_params();
    $current_user_id = get_current_user_id();
    return update_user_meta($current_user_id, 'user_likes',$body);
};

And then on the front end, here is my POST request:然后在前端,这是我的 POST 请求:

handleLike(){
      fetch(`https://site-url.com/wp-json/v1/user_likes/${this.$store.state.userInfo.id}`,{
        method:"POST",
        body:JSON.stringify({
          post_id:this.currentPost.id,
          post_title:this.currentPost.title.rendered
        }),
         headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${this.$store.state.accessToken}`
        },
      }).then(resp=>resp.json())
      .then(data=>console.log(data)) 

My GET request is also returning false.我的 GET 请求也返回 false。

The issue I believe is that I am not retrieving the current user ID because according to docs for get_user_meta and update_user_meta, if user id is not determined, the function will return false.我认为的问题是我没有检索当前用户 ID,因为根据 get_user_meta 和 update_user_meta 的文档,如果未确定用户 ID,function 将返回 false。 Why the user id is not being determined, I don't know.为什么没有确定用户ID,我不知道。 As I mentioned, I am using the JWT Authorization for WP REST API.正如我所提到的,我正在使用 WP REST API 的 JWT 授权。 Therefore based on my reading, I do not need to generate a nonce because WP will use the token to determine the current user.因此,根据我的阅读,我不需要生成随机数,因为 WP 将使用令牌来确定当前用户。 Let me know if I am wrong about that.让我知道我是否错了。 Any guidance would be greatly appreciate.任何指导将不胜感激。

Try this, set credentials & headers as in the example:试试这个,设置credentials & headers ,如示例中所示:

method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cache-Control': 'no-cache',
      },
      body: params
    })

the corse can be managed by adding this to functions.php可以通过将其添加到functions.php来管理corse

function my_customize_rest_cors() {
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: POST, GET' );
        header( 'Access-Control-Allow-Credentials: true' );
        header( 'Access-Control-Expose-Headers: Link', false );
        header( 'Access-Control-Allow-Headers: X-Requested-With' );
        return $value;
    } );
}

add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );

Figured out my issue.想通了我的问题。 For future users using the JWT Authorization For WP REST API and hosting their Wordpress database on AWS Lightsail, here is how the .htaccess file must be stored on Bitnami's SSH: For future users using the JWT Authorization For WP REST API and hosting their Wordpress database on AWS Lightsail, here is how the .htaccess file must be stored on Bitnami's SSH:

<Directory "/opt/bitnami/apps/wordpress/htdocs”>
<IfModule mod_rewrite.c>RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>
</Directory>
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

Second issue I had: The token is already a string.我遇到的第二个问题:令牌已经是一个字符串。 Therefore putting it in a template literal causes parsing issues.因此将它放在模板文字中会导致解析问题。 Using a simple concatenation will do.使用简单的连接就可以了。

Here are the changes I made to authorization in the header (Note: this is using Vue's Vuex):以下是我在 header 中对授权所做的更改(注意:这是使用 Vue 的 Vuex):

"Authorization": "Bearer" + this.$store.state.accessToken

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM