cancel
Showing results for 
Search instead for 
Did you mean: 

CROS error on magento2 while using external API

CROS error on magento2 while using external API

I am trying to access an api using jquery in magento2

Here is my jquery code

<script>require(['jquery'],function(){
    jQuery(document).ready(function() {
        jQuery(".result").hide();
        jQuery("#form_value").submit(function(){
            
         

            var url = "https://url.com";
            jQuery.ajax({
            url: url,
            type: "GET",
           
            showLoader: true,
            cache: false,
            success: function(response){
                console.log(response.output);
                jQuery(".result").show();
                jQuery(".result").text(response.output);
            }
        });
        return false;
        });
    });
});</script>

But i am getting error as CROS policy error .. i have added following code in .htacess but still getting same error

SetEnvIf Accept application/json API
Header always set Access-Control-Allow-Origin "*" env=API
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT" env=API
Header always set Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization" env=API

anything that i am missing?

1 REPLY 1

Re: CROS error on magento2 while using external API

Nginx Not pass Access-Control-Allow-Origin

by using the below module it will pass the header in API
It can update from Store >> Config >> General >> WEb Change * to any URL you want to access

https://github.com/splashlab/magento-2-cors-requests

If issue solved, Click Kudos & Accept as Solution.
LitCommerce - The Most Simple & Affordable Multi-channel Selling Tool