3

Having a Perl Catalyst application, which produces JSON, I need to read that JSON content using jQuery within an HTML page, served by an Apache server. Both applications, Catalyst and Apache are running on the same host.

When I access the Catalyst URL from Apache I get the error

Access to XMLHttpRequest at 'http://localhost:3000/abc/json_list' from origin 'http://localhost:8888' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As I red in many topics, a header (or more) must be set. In this case the Catalyst must be set but I don't know how.

Any hint?

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 1
    You don't show any relevant code. Please [edit] your post to show the relevant code generating the response. You set headers in a Catalyst application by calling the `->header(...)` method of [Catalyst::Response](https://metacpan.org/pod/Catalyst::Response#$res-%3Eheader), so that's where I would start. – Corion Feb 05 '19 at 08:14
  • So for the applications to be considered same-origin, it’s not enough for both apps to be running on the same server. The two applications must also be served with the exactly the same hostname, and same port number, and the same protocol (both http or both https). Otherwise browsers will consider any request to be a cross-origin request if it’s made by your frontend JavaScript code running on the Apache server to the Perl Catalyst server. So that’s why you need to CORS-enable the Perl Catalyst server. For that, see http://lists.scsys.co.uk/pipermail/catalyst/2018-June/thread.html#30639 – sideshowbarker Feb 05 '19 at 08:46

1 Answers1

6

Catalyst allows you to set response headers using the header method on the response object.

$c->res->header( "Access-Control-Allow-Origin" => "http://localhost:8888" );

Consider using a controller's sub auto or using existing middleware if you have multiple endpoints that need to provide permission via CORS.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335