Set CORS Headers
-
Hey there,
I added my own CORS Allow-Origin: “*” Headers to the WP-API to enable it for hybrid app usage. I did this with the following code:
function wfp_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: 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', 'wfp_rest_cors', 15 );
After enabling the plugin these headers were only sent on the first (non cached) response, but never with the cached response. Since probably the ‘rest_api_ini’ hook isn’t used there.
I saw in Update 2019.1.6, that filters were added to manipulate these headers. But I somehow couldn’t figure out how to set the headers like above. Is there a code-example of how to add/overwrite headers using this filter?
Currently the only way I got it to work is by hard coding these headers into the plugin – which is obviously bad practice and should be avoided, so I would appreciate any help into the right direction.
Thanks a lot – Great Plugin! – And have a nice day.
Florian,
- The topic ‘Set CORS Headers’ is closed to new replies.