从跨域的wp rest api获取数据

时间:2018-06-23 07:37:34

标签: wordpress wordpress-rest-api

我试图从跨域的js应用程序从wordpress rest api获取数据,我遇到了 Access-Control-Allow-Origin 错误

axios.get(`https://bikeguy.xyz/wp-json/wp/v2/posts?categories=86`)
			.then( posts => console.log(posts) )
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

enter image description here

为了允许跨域访问,我将这些代码放入了 functions.php 文件中,但仍然出现相同的错误

// Hook.
add_action( 'rest_api_init', 'wp_rest_allow_all_cors', 15 );
/**
 * Allow all CORS.
 *
 * @since 1.0.0
 */
function wp_rest_allow_all_cors() {
    // Remove the default filter.
    remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    // Add a Custom filter.
    add_filter( 'rest_pre_serve_request', function( $value ) {
        header( 'Access-Control-Allow-Origin: *' );
        header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
        header( 'Access-Control-Allow-Credentials: true' );
        return $value;
    });
} // End fucntion wp_rest_allow_all_cors().

1 个答案:

答案 0 :(得分:0)

我想再添加一个过滤器来防止这种情况发生。

危险!请勿在生产中或无条件使用。

add_filter( 'rest_authentication_errors' , function() {
   wp_set_current_user( 1 );
}, 101 );

或全功能:

function wp_api_allow_cors() {
  remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  add_filter( 'rest_pre_serve_request' , function( $value ) {
    header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce,Content-Type, X-Requested-With');
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
    header( 'Access-Control-Allow-Credentials: true' );
    return $value;
  });

  // Danger: Don't use in the production or without condition.
  $domains = array( 'localhost', 'mydomain.com' );
  if ( in_array( $_SERVER['SERVER_NAME'], $domains ) ) {
    add_filter( 'rest_authentication_errors' , function() {
      wp_set_current_user( 1 );
    }, 101 );
  }
}

add_action( 'rest_api_init', 'wp_api_allow_cors', 15 );
相关问题