微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从本地主机访问 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。