Magento 2 – Access to XMLHttpRequest Blocked

magento2rest api

access to XMLHttpRequest 'api link' from origin 'http://localhost:8100' has 
been blocked by cors policy: response to perflight doesn't pass access to 
contrsol check: it doesn't have http ok status

I've built magento apis and my partner call those apis through ionic and get that error
I have added following lines to .htaccess file in magento root directory:

<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge"
<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
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
    Header always set Access-Control-Allow-Headers "X-Accept-Charset,X-Accept,Content-Type"
</FilesMatch>

and added those lines to httpd.conf in apache:

<Directory />
AllowOverride none
Require all denied
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header set Access-Control-Allow-Headers "X-Accept-Charset,X-Accept,Content-Type"
</Directory>

Best Answer

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood.

It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.

A preflight request is automatically issued by a browser when needed. In normal cases, front-end developers don't need to craft such requests themselves.

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

Magento 2 Api does not support pre-flight request by default. You can modify the apache or nginx server config for handling the request. For example http://snippi.com/s/or2myzn

I would suggest installing the following module for handling the CORS pre-flight request in Magento 2 Api:

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

Related Topic