2

I'm getting an error while call API from Angular APP
test website and app is hosted in different domain.

  • Website Url abc.test.com
  • Angular App : xyz.test.com

When I call API for Listing Of product in getting below Error

Failed to load resource: the server responded with a status of 400 () Access to XMLHttpRequest at 'https://abc.test.com/rest/V1/products?searchCriteria%5BpageSize%5D=10&searchCriteria%5BcurrentPage%5D=1&searchCriteria%5BsortOrders%5D%5B0%5D%5Bdirection%5D=DESC&searchCriteria%5BsortOrders%5D%5B0%5D%5Bfield%5D=created_at' from origin 'http://xyz.test.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to solved it?

4

4 Answers 4

9
+200

Nginx Not pass Access-Control-Allow-Origin

by using 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

2

You may try to create a PHP script as described below and after that instead calling Magento 2 API directly from the angular app (xyz.test.com), call this PHP script with some parameter. In the PHP script, you can add Access-Control-Allow-Origin to the header.

It is not the best solution but works.

step 1)

Create a PHP file under Magento 2 root

Please change Site Url , API User name and API Password in the script.

File: apiconnect.php

<?php
header("Content-type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *")
$magentoSiteUrl = 'http://www.YOUR-SITE.com';
$userData = array("username" => 'A_ADMIN_USERNAME', "password" => 'A_ADMIN_PASSWORD');
define('MAGENTO_SITE_URL',$magentoSiteUrl);
$ch = curl_init($magentoSiteUrl."/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData)))); 
$token = curl_exec($ch); // get access Token, use it for API call
$jobName = $_REQUEST['jobname'];

switch ($jobName){

    case 'getproducts':
     getProductsData($token);
     break; 

    default:
     echo "Not Job Name found in request";
     break;
}




function getProductsData($accToken)
{


    $searchCriteria='';
    $searchCriteria .= 'searchCriteria[filter_groups][0][filters][0][field]=sku&';
    $searchCriteria .= 'searchCriteria[filter_groups][0][filters][0][value]=ABC123&';
    $searchCriteria .= 'searchCriteria[filter_groups][0][filters][0][condition_type]=eq';

    $ch = curl_init(MAGENTO_SITE_URL."/index.php/rest/V1/products/search?".$searchCriteria);    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($accToken)));     
    $result = curl_exec($ch);    
    echo $result;    
}

step 2)

From your angular app (xyz.test.com) access to Magento API using URL like

www.my-magento-siteurl.com/apiconnect.php?jobname=getproducts

0

Easiest way is to add Allow origin to your .htaccess in home directory into your .htacess search for

<IfModule mod_headers.c>

and insert the follwing code :

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

your .htaccess file will be look like this at the end :

<IfModule mod_headers.c>

    Header set X-UA-Compatible "IE=edge"

    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

    # `mod_headers` cannot match based on the content-type, however,
    # the `X-UA-Compatible` response header should be send only for
    # HTML documents and not for the other resources.

    <FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt[cf]|txt|vcard|vcf|vtt|webapp|web[mp]|webmanifest|woff2?|xloc|xml|xpi)$">
        Header unset X-UA-Compatible
    </FilesMatch>

</IfModule>
1
  • 1
    How to do same in the Nginx server?
    – Mukesh
    Commented May 19, 2021 at 18:49
0

2023

In newer version, please use https://github.com/graycoreio/magento2-cors

Maintainer of splashlab/magento-2-cors-requests already confirmed that he no longer maintains this module. Checkout here: https://github.com/splashlab/magento-2-cors-requests/issues/11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.