从本地主机访问 Magento 2.3.6 REST API - 被 CORS 策略阻止 将以下几行添加到 .htaccess并且在 magento 2.4.1 必须注释 #RewriteBase on .htaccess然后将以下几行添加到 .htaccess 上的 IfModule mod_headers.c>

问题描述

从本地主机访问 Magento REST API 返回错误被 CORS 政策阻止

我在邮递员上使用“邮递员生成代码片段”生成代码,它工作正常,但在 axios 和其他类型的 ajax 请求中不起作用

var axios = require('axios');
var data = JSON.stringify({


"customer": {
    "email": "adnanEmi@Shanal.tr","firstname": "Adnan","lastname": "Semi","groupId":3,"addresses": [
      {
        "defaultShipping": true,"defaultBilling": true,"region": {
          "regionCode": "NY","region": "New York","regionId": 43
        },"postcode": "10755","street": [
          "Address Details"
        ],"city": "Istanbul","telephone": "00000000","countryId": "TR"
      }
    ]
  },"password": "#######"
});

var config = {
    method: 'post',url: 'https://blablabla.tr/rest/V1/customers',headers: {
        'Content-Type': 'application/json','Cookie': 'PHPSESSID=9e952ab096c07bf2851826b05454f8de'
    },data: data
};

axios(config)
    .then(function(response) {
        console.log(JSON.stringify(response.data));
    })
    .catch(function(error) {
        console.log(error);
    });

}

解决方法

这对我有用 magento 2.3.6 和 2.4.1 rest api

将以下几行添加到 .htaccess

上的 IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ "index.html" [R=200,E=API:1,PT]

并且在 magento 2.4.1 必须注释 #RewriteBase on .htaccess

然后将以下几行添加到 .htaccess 上的 IfModule mod_headers.c>

SetEnvIf Accept application/json API
Header always set Access-Control-Allow-Origin "*" env=API<br/>
### ----- the below line is optional -----
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