Search code examples
perlcorsmojoliciousmojolicious-lite

Allow CORS with Mojolicious::Plugin::SecureCORS


I am new to Mojolicious and using plugins especially SecureCORS. How can I allow CORS on POST requests?

I managed to allow CORS for GET with following lines:

use Mojolicious::Lite;

app->plugin('SecureCORS');
app->routes->to('cors.origin' => '*');

I thought 'cors.origin' => '*' is allowing CORS for all methods but it works only for GET.

Maybe there is another or better way to send the Access-Control-Allow-Origin header and allow all POST, GET, PUT, ...


Solution

  • Frankly said, I have not used SecureCors plugin but I faced the same problem of cross-origin problem while developing the REST API's in Mojolicious.

    Note:- I am not using the Mojolicious::lite app.

    You might need to do something more or less similar to this, under your startup subroutine (If not using Mojolicious::Lite).

    $self->hook(after_dispatch => sub { 
        my $c = shift; 
        $c->res->headers->header('Access-Control-Allow-Origin' => '*'); 
        $c->res->headers->access_control_allow_origin('*');
        $c->res->headers->header('Access-Control-Allow-Methods' => 'GET, OPTIONS, POST, DELETE, PUT');
        $c->res->headers->header('Access-Control-Allow-Headers' => 'Content-Type' => 'application/x-www-form-urlencoded');
    
    }); 
    

    I hope it helps.