【问题标题】:Consumer is not authorized to access angular 2 REST api from Magento 2消费者无权从 Magento 2 访问 Angular 2 REST api
【发布时间】:2017-04-12 06:42:07
【问题描述】:

我正在使用 Angular 和 magento 2 调用 Http 请求。

我使用我的 Magento2 REST api 端点使用 HTTP GET 请求来做同样的事情。

更新:

///<reference path="../node_modules/angular2/typings/browser.d.ts" />
import "rxjs/add/operator/map";
import {Component, Input} from 'angular2/core';
import {Request, Response,Http} from 'angular2/http';
import {Request,Headers,RequestOptions, Response,Http} from 'angular2/http';


interface Person {
    //name: string;
    //age: number;
}

@Component({
    selector: 'my-app',
    template: `<h1>My First Angular 2 App</h1>
    <div>{{people | json}}</div>
    `
})
export class AppComponent {
    @Input() private people: Person[];

 constructor(private http: Http) {
   }

   public ngOnInit() {
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('Authorization', 'Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://10.../Mage_ang2/index.php/rest/V1/customers/1',options)
        .map(response => console.log(response.json))
         .subscribe((items: Person[]) => {    //updated
            console.log('items: ' + items);
            this.people = items;
        }, error => console.log(error));
    }
}

使用 .subscribe() 我得到:

app/app.component.ts(32,15): 错误 TS2345: '(items: Person[]) => void' 类型的参数不可分配给'NextObserver |错误观察者 |完成观察者 | ((值:无效)=> 无效)'。 [0] 类型 '(items: Person[]) => void' 不可分配给类型 '(value: void) => void'。 [0] 参数“items”和“value”的类型不兼容。 [0] 类型 'void' 不能分配给类型 'Person[]'。

XMLHttpRequest 无法加载预检响应具有无效的 HTTP 状态代码 400

【问题讨论】:

  • 检查访问显示更多日志

标签: angular


【解决方案1】:

您需要在标头中设置授权,而不是作为查询参数发送。

你的 http 获取方法:

this.http.get('http://10.12.13.1/Mage_ang2/index.php/rest/V1/products/10090-White-XL?Authorization=Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

请删除?Authorization=Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22 并设置标题如下

let headers = new Headers({ 'Accept': 'application/json' });
headers.append('Authorization', 'Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

let options = new RequestOptions({ headers: headers });
return this.http
.get('http://10.12.13.1/Mage_ang2/index.php/rest/V1/products/10090-White-XL',options)
.map(res => console.log(res));

别忘了在你的 ts 文件中导入 RequestOptions 和 Headers

import {Http, Headers, RequestOptions} from '@angular/http';

【讨论】:

  • 如果你想在页面加载的时候调用它,只要把它放在ngOnInit中就可以了。
  • 端口 3000 是您的应用程序运行端口。
  • 我刚刚给你提示过如何做到这一点。现在,我已经更新了正确的代码。只需将 _http 更改为 http 并使用您的获取 url 更改 _url。
  • 已更新代码@digit,API 没有响应!
  • 你试过用 REST 工具测试 url,结果如何。
猜你喜欢
  • 2022-01-25
  • 2014-02-14
  • 2023-02-07
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
相关资源
最近更新 更多