Json 无法获取angular 2中Rest api的http请求
我正在尝试使用在magento 2中创建的Rest api在angular 2前端获取http get请求 \var\www\html\Angular2\sample ng http master\web\app\app.component.tsJson 无法获取angular 2中Rest api的http请求,json,angular,magento2,Json,Angular,Magento2,我正在尝试使用在magento 2中创建的Rest api在angular 2前端获取http get请求 \var\www\html\Angular2\sample ng http master\web\app\app.component.ts ///<reference path="../node_modules/angular2/typings/browser.d.ts" /> import "rxjs/add/operator/map"; import {Component,
///<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))
}
}
///
导入“rxjs/add/operator/map”;
从'angular2/core'导入{组件,输入};
从'angular2/Http'导入{Http};
接口人{
//名称:字符串;
//年龄:人数;
}
@组成部分({
选择器:“我的应用程序”,
模板:`我的第一个Angular 2应用程序
{{people | json}}
`
})
导出类AppComponent{
@输入()个人:个人[];
构造函数(专用http:http){
}
公共ngOnInit(){
this.http.get('http://10.20.1.2:3000/data.json')
.map(响应=>{
log(response.json);
log(response.json());
返回response.json()
})
.订阅((项目:个人[])=>{
console.log('items:'+items);
这个人=物品;
},error=>console.log(错误))
}
}
这里,如果我尝试获取json文件(),如图所示,我就能够获得json响应
我需要的是像这样传递Magento 2的API端点:
如果我从Postman客户端调用,上面的rest端点工作得非常好
如果我在app.component.ts文件中使用相同的URL(),我会得到:
如果我使用端口3000为()的URl,我得到:
响应{u body:“无法获取/Mage_ang2/index.php/rest/V1/customers/1↵", 状态:404,状态文本:“确定”,标题:标题,类型:2
我缺少哪个部分?您需要设置标题: 访问控制允许来源:“您的服务器地址” 及 访问控制允许标头:“访问控制允许来源”
这是个问题。您需要添加标题:
/**
* 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);
}
}
太长了,读不下去了?你需要设置访问控制允许原点?TL;MaGeto服务器不允许其他服务器进行调用。你需要配置访问控制允许标题来解决这个问题。请告诉我需要在哪里设置页眉?在我的REST API URL中吗?你需要为你的REST API响应设置标题。这里是MaGeto的Excel。:还有:在一些解决方法之后,一种建议的设置方法是这样的:在magento的.htaccess文件中设置头文件Access Control Allow Origin“*”。然后我得到响应{u body:“Cannot GET/magento2/index.php/rest/V1/customers/1↵,状态:404,状态文本:“确定”,标题:标题,类型:2…