Wordpress 从跨域的wp rest api获取数据
我试图从跨域的js应用程序中从wordpress rest api获取数据,我得到了访问控制允许源代码错误Wordpress 从跨域的wp rest api获取数据,wordpress,wordpress-rest-api,Wordpress,Wordpress Rest Api,我试图从跨域的js应用程序中从wordpress rest api获取数据,我得到了访问控制允许源代码错误 axios.get(`https://bikeguy.xyz/wp-json/wp/v2/posts?categories=86`) .then(posts=>console.log(posts)) 我想再添加一个过滤器来防止出现这种情况 危险请勿在生产中使用或无条件使用 add_filter( 'rest_authentication_errors' , function() {
axios.get(`https://bikeguy.xyz/wp-json/wp/v2/posts?categories=86`)
.then(posts=>console.log(posts))
我想再添加一个过滤器来防止出现这种情况
危险请勿在生产中使用或无条件使用
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 );
你可能需要修改你的JS代码,你还没有把它放到你的问题上(但你应该这么做)。检查这个使用jsonp的答案:请显示您的javascript,在我从JSFIDLE安装的一个WP上尝试了这个,效果很好。请注意,您的url是错误的。应该是/wp json/wp/v2/posts,这很可能是问题所在。@ElvinHaci wp rest API返回常规json,问题可能是他的url错误。@RickCalder我添加了我的js代码我不知道,它在JSFIDLE中工作,但在我的vue应用程序中不工作