Magento – How to enable CORs to access Magento rest APIs : Magento2

angularjsapimagento2nginx

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?

Best Answer

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