我试图通过使用Angular 4服务从我的本地服务器127.0.0.1获取JSON数据,但我无法将它们发送到我的Angular App。 I got this error。 this is my JSON data on 127.0.0.1
注意:我使用XAMPP作为我的服务器[localhost(127.0.0.1)]
这是我的app.component.ts
import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private http: Http){}
ngOnInit()
{
this.http.get('http://127.0.0.1/wordpress/getdata.php?Name=json')
.subscribe(
(res: Response)=>
{
const name = res.json();
console.log("This is the response", name);
}
)
}
}
这是app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
由于您从127.0.0.1:4200调用127.0.0.1:80,因此它们被视为单独的主机。这个术语意味着CORS适用。
跨域资源共享(CORS)是一种机制,允许从提供第一个资源的域外的另一个域请求网页上的受限资源(例如字体)。
使用webpacks devserver来解决此代理到127.0.0.1:80的请求。
https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
proxy.conf.json
{
"/wordpress": {
"target": "http://localhost:80",
"secure": false
}
}
然后从同一主机
调用它 http://localhost:4200/wordpress/getdata.php?Name=json