Closed wujekbogdan closed 5 years ago
Why exactly it means "it does not works"?
Code looks fine to me, assuming the Origin
header is part of the AJAX request, and your logic is correct, it should work.
You can try:
$routes
->addRoute(new ActionRoute(
self::TRANSACTION_REGISTRATION_URI,
function () {
$this->registerTransaction();
die;
},
[
'method' => 'POST',
'before' => function () {
$origin = get_http_origin(); // assumes "Origin" header is part of the request
if ($origin) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
}
},
]
))
Please make sure Origin
header is set, or it will not work because get_http_origin()
will return an empty string.
If the Origin
header is set, then my snippet should work... and that point, it should also work by using send_origin_headers()
as "before" callback, plus using allowed_http_origins
filters that will be triggered if:
get_http_origin()
returns something, andsend_origin_headers()
is calledSo:
add_filter('allowed_http_origins', function ($allowed) {
return array_merge((array)$allowed, $this->config->get('ajax:allowed_hosts'));
});
$routes
->addRoute(new ActionRoute(
self::TRANSACTION_REGISTRATION_URI,
function () {
$this->registerTransaction();
die;
},
[
'method' => 'POST',
'before' => 'send_origin_headers',
]
))
should work as well assuming that:
get_http_origin()
returns something non-emptyget_http_origin()
returns, is included in what $this->config->get('ajax:allowed_hosts')
returns.@gmazzap
I'm sorry. You're right - the code I posted is OK. It turned it that it was a front-end issue.
Thanks for the explanation anyway, because your post helped me to identify the front-end bug.
Cool. Will close the issue then.
Hi,
I'd like to use Cortex to handle AJAX requests, but I have a problem with CORS. I cannot use the
allowed_http_origins
filter because this filter only affects AJAX requests that are performed in a standard WordPress way.Is there any way to send origin headers before the request is handler by Cortex?
I tried to call
send_origin_headers()
within thebefore
callback, but it doesn't work.