I have read multiple entries in the WP Codex, numerous articles and Stack Exchange questions. I have a fully functioning API for a private plugin I am developing, but when moving it into production on WPEngine, the endpoint that served text/html
is having CORS and CORBS issues. I have tried setting the headers just for that route but nothing seems to be working. It worked fine locally, and on our dev servers.
Why serve HTML
you ask?
My plugin connects a WP form I created in React.JS, via an Admin Portal, with our CRM, via another API from our IIS .Net Server. Once someone submits a form, the API takes over the transaction and matches HTML
I serve with some other internal data to send an email. We want to keep this system centralized for security, maintenance and more importantly cross-platform purposes (We have other tech stacks we serve).
So What is Happening?
I can hit my endpoint from the browser and the html renders. I can even get the html from RESTlet/Postman. However, when I try to make a GET
request to the URL from our internal API, the server is not allowing the request.
Here is the setup:
Sending Response
//callback for register_rest_route
function proxy_email($request) {
//some validation, db queries and other stuff
header( 'Content-Type: text/html; charset=UTF-8' );
echo $html_email;
exit();
}
Handling Cors
//handling cors
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $served, $result, $request, $server ) {
$origin = get_http_origin();
$route = $request->get_route();
$allowed_origins = array(
//the local, dev, and production origins plus the following:
site_url()
);
// the route I set up for the email includes the string 'thankyou'
if ( $origin && in_array( $origin, $allowed_origins ) && preg_match( "/(thankyou)/", $route ) != 1) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: Content-Type, X-WP-Nonce');
} else if ( $origin && in_array( $origin, $allowed_origins ) && preg_match( "/(thankyou)/", $route ) == 1 ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: OPTIONS, GET');
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: Content-Type');
header( 'Content-Type: text/html; charset=UTF-8');
header( 'Accept: */*');
}
return $served;
}, 10, 4);
Is there an issue with my approach, is this a WP issue, or is this a WPEngine Issue, or is this something else?