I have a WordPress backend where I have added my own custom endpoints to the API:
// retrieve countries
register_rest_route( $namespace, '/countries',
array(
'methods' => 'GET',
'callback' => array( $this, 'get_countries' ),
)
);
// check answer
register_rest_route( $namespace, '/check_answer',
array(
'methods' => 'POST',
'callback' => array( $this, 'check_answer' ),
)
);
I have set up my environment like this: https://example.com is where the React application lives, and WordPress is in a subdirectory, on https://example.com/wp
My React application makes POST and GET requests to those endpoints above. I have a production environment variable where I set the base URL of the API, which is https://example.com/wp/wp-json/game
('game' is my namespace) and so I can make requests with Axios to https://example.com/wp/wp-json/game/countries
and https://example.com/wp/wp-json/game/check_answer
and here comes the issue.
My server is configured so that it serves the React application both with as without www
. So https://example.com and https://www.example.com both serve the same application.
But this generates some interesting issue for my custom endpoints: the GET request always works. but the POST request only works if I am trying it from https://example.com, NOT from https://www.example.com . In case of the latter it just simply shows me a failed request. No response, nothing.
I have googled and it seems to be related to CORS, but I was unable to fix it. Any ideas here?