經過上一章節的設定後,我們現在就來取得 WP 的資料。
我們在頁面上向其他網域提取資料時,如果沒有在 server 檔案的 header 做設定,要做跨網域存取會被擋掉。
這邊提供幾個方法來解決 WP rest-api 的跨域存取。
方法一 在 functions.php 加入設定
function add_custom_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; } ); } add_action( 'rest_api_init', 'add_custom_headers', 15 );
如果只想允許部分網域存取請改成:
function add_custom_headers() { add_filter( 'rest_pre_serve_request', function( $value ) { $origin = get_http_origin(); $allowed_origins = [ 'site1.example.com', 'site2.example.com', 'localhost:3000' ]; if ( $origin && in_array( $origin, $allowed_origins ) ) { header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) ); } header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce,Content-Type, X-Requested-With'); header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' ); header( 'Access-Control-Allow-Credentials: true' ); return $value; } ); } add_action( 'rest_api_init', 'add_custom_headers', 15 );
方法二 使用 .htaccess
大部分的 PHP 主機都使用 Apache,所以可以在 wp 目錄下的 .htaccess 簡單的加上檔案的路徑(通常是網址 + /wp-json/wp/v2/
# .htaccess
# 放在 WP 網站所在的資料夾
<If "%{REQUEST_URI} =~ /wp-json/wp/v2/">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</If>
如果你是從 server side 發 request 則沒有這類問題。 加好之後,差不多就可以進入實作的部分。