2017-04-11 67 views
-1

林REST API的http请求试图让HTTP GET在Magento建立在使用REST API角2前端请求2.不能获得在角2

\ VAR \ WWW \ HTML \ Angular2 \样本-NG -http主\网络\程序\ app.component.ts

///<reference path="../node_modules/angular2/typings/browser.d.ts" /> 
import "rxjs/add/operator/map"; 
import {Component, Input} from 'angular2/core'; 
import {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() { 
    this.http.get('http://10.20.1.2:3000/data.json') 
     .map(response => { 
      console.log(response.json); 
      console.log(response.json()); 
      return response.json() 
     }) 
     .subscribe((items: Person[]) => { 
      console.log('items: ' + items); 
      this.people = items; 
     }, error => console.log(error)) 
} 
} 

这里如果我试图让JSON文件(http://10.20.1.2:3000/data.json)如图所示,林抽到了JSON响应。

我需要的是我需要传递的Magento 2的API端点这样的:

http://10.20.1.2/Magento2/index.php/rest/V1/customers/1

上述其余端点完美的作品,如果我从邮递员客户端调用。

如果我在app.component.ts文件中使用相同的URL(http://10.20.1.2/Magento2/index.php/rest/V1/customers/1)我得到:

enter image description here

如果我使用的URL与端口3000为:(http://10.20.1.2:3000/Magento2/index.php/rest/V1/customers/1)我得到:

响应{_body: “不能让/Mage_ang2/index.php/rest/V1/customers/1↵”,状态:404,状态文本: “OK”,标题:接头,类型:2 ...

我错过了哪个部分?

+1

你设置头访问控制允许来源? – giaco

回答

1

您需要设置标题:

访问控制允许来源: 'your_angular_server_address'

访问控制允许信头:“访问-Control-Allow-Origin'

它是CORS问题。

+0

TL; DR Magento服务器不允许其他服务器拨打电话。您需要配置Access-Control-Allow-Headers来解决此问题。 – Stefan

+0

你能告诉我需要设置标题吗?它在我的Rest API网址中吗? – Sach

+0

您需要为您的REST API响应设置标题,这里以magento为例:http://magento.stackexchange.com/questions/92105/magento-2-sending-a-custom-header-response-from-a-controller 和那里:https://www.kathirvel.com/magento-returning-json-for-ajax-and-api-calls-response-from-controller-action/ – giaco

0

您需要添加标题:

/** 
    * Interceptor set the headers for the request. 
    * Params: 
    * - objectToSetHeadersTo: Request or Arguments that will contain the headers. 
    **/ 
    private setHeaders(objectToSetHeadersTo: Request | RequestOptionsArgs) { 
    const headers = objectToSetHeadersTo.headers; 
    headers.set('Content-Type', 'application/json'); 
    if (this.token) { 
     headers.set('Authorization', 'Token ' + this.token); 
    } 
    }