rest api 发送请求前验证用户的生产力

Published
2023-02-26
浏览次数 :  110

// Check current user's capabilities before sending REST API request
function sendRestApiRequest() {
    // Get information about the currently logged-in user
    fetch('/wp-json/wp/v2/users/me')
        .then(response => response.json())
        .then(user => {
            // Check if user has the edit_posts capability
            if (user.capabilities.edit_posts) {
                // User has the edit_posts capability, send REST API request
                fetch('/wp-json/wp/v2/posts', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + user.token
                    },
                    body: JSON.stringify({
                        // Add post data here
                    })
                })
                .then(response => response.json())
                .then(data => {
                    // Handle response data
                });
            } else {
                // User doesn't have the edit_posts capability, show error message
                console.log('User does not have the edit_posts capability');
            }
        });
}

jquery版本

// Set up the AJAX request
var ajaxUrl = 'https://example.com/wp-json/wp/v2/posts';
var ajaxData = {
  title: 'New post title',
  content: 'New post content'
};

// Check user capability before sending the AJAX request
$.ajax({
  url: 'https://example.com/wp-json/wp/v2/users/me',
  method: 'GET',
  xhrFields: {
    withCredentials: true
  }
}).done(function(response) {
  if (response.capabilities.edit_posts) {
    // User has the edit_posts capability, so send the AJAX request to create a new post
    $.ajax({
      url: ajaxUrl,
      method: 'POST',
      data: ajaxData,
      xhrFields: {
        withCredentials: true
      }
    }).done(function(response) {
      console.log('Post created!');
      console.log(response);
    }).fail(function(jqXHR, textStatus, errorThrown) {
      console.error('Error creating post:', errorThrown);
    });
  } else {
    // User does not have the edit_posts capability, so display an error message
    console.error('User does not have the edit_posts capability.');
  }
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.error('Error getting user data:', errorThrown);
});

  • 标签1
  • 标签1
  • 标签1
Top