【问题标题】:Magento 2 API with Angular 2 Token authentication具有 Angular 2 令牌身份验证的 Magento 2 API
【发布时间】:2017-08-10 07:41:28
【问题描述】:

这是集成问题。非常感谢您的帮助(提示 || 指南)

我在本地安装了 Angular2 和 Magento2 (bitnami)。 Magento conf 已更改为具有 CROS 的正确标题(见下文)。 我从 Angular2 调用 Magento2 来获取令牌,我遇到了以下问题:

选项http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token 400(错误请求) XMLHttpRequest 无法加载 http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token。预检响应包含无效的 HTTP 状态代码 400

异常:响应状态为:0,URL 为空

角 2 面:

let headers = new Headers({'Content-type': 'application/json'});
 headers.append('Access-Control-Allow-Origin', '*');
 headers.append('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE');
 headers.append('Access-Control-Allow-Headers', 'Origin,Authorization,X-Auth-Token,Accept,Content-Type');
 headers.append('Access-Control-Allow-Credentials', 'true'); 
 let options = new RequestOptions({ headers: headers });
return this.http.post( 'http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token',
                      JSON.stringify('{"username":"angUser", "password":"angUser2017"}'),
                      options)
                      .map(res => res.json());

Magento2 API 用户 angUser / angUser2017 消费者密钥:5bhvi7gjvyafcp35rajuxh0y4me2plga 消费者秘密:yh1nefyw1u80rd0ip1q6f8pijv9x72f1 访问令牌:g5plfwth2rhlwtuwfhhqp7mg6sebrxc3 访问令牌秘密:i1f4t7j65oo8ydtnteub9xr7wrswe99c

Magento 标头: 响应标头 访问控制允许凭据:真 Access-Control-Allow-Headers:来源、内容类型、接受、授权 访问控制允许方法:GET、POST、OPTIONS、PUT、DELETE 访问控制允许来源:*

【问题讨论】:

    标签: api angular authentication token magento2


    【解决方案1】:

    我之前遇到过类似的问题,我追踪到this method 没有检查->isOptions()。因此,来自另一个域的每个 API 调用都会触发 Request method is invalid 异常。

    /**
     * Retrieve current HTTP method.
     *
     * @return string
     * @throws \Magento\Framework\Exception\InputException
     */
    public function getHttpMethod()
    {
        if (!$this->isGet() && !$this->isPost() && !$this->isPut() && !$this->isDelete()) {
            throw new \Magento\Framework\Exception\InputException(new Phrase('Request method is invalid.'));
        }
        return $this->getMethod();
    }
    

    如果您使用的是 apache,您可以在 github forum 中找到可能的解决方法。

    在我的具体情况下,我最终做的是为同一域的前端和 api 提供服务,以避免 CORS 出现问题(我使用 nginx)。

    为此所需的配置示例如下:

    location ~ ^/(index.php/)?rest {
      try_files $uri $uri/ /index.php?$args;
    }
    
    location / { 
      root /var/www/angular/public/;
      index index.html;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-25
      • 2017-02-03
      • 2018-11-20
      • 2013-12-02
      • 2013-11-25
      • 2014-07-06
      • 1970-01-01
      • 2017-07-27
      • 2017-06-28
      相关资源
      最近更新 更多