2017-07-07 60 views
1

我想通过使用Angular 4服务从我的本地服务器127.0.0.1获取JSON数据,但是我无法获取他们对我的角应用程序。 I got this errorthis is my JSON data on 127.0.0.1Angular 4 Http GET方法不能在localhost(127.0.0.1)上获取JSON数据

注:我用XAMPP我的服务器[本地主机(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

由于您从127.0.0.1:4200呼叫127.0.0.1:80,因此它们被视为单独的主机。这意味着CORS适用。

跨域资源共享(CORS)是一种机制,允许从第一个资源所服务的域之外的其他域请求网页上的受限资源(例如字体)。

为了解决这个代理请求到127.0.0.1:80与webpacks devserver。

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

+0

你的解释是明确的调用它,但它并没有为我工作。所以我尝试使用我自己的网络服务器,它是[链接](http://myappfact.com),我改变了我的app.component.ts' this.http.get('http://myappfact.com/getdata。 php?Name = json')' 它显示不同的错误,即** XMLHttpRequest无法加载http://myappfact.com/getdata.php?Name=json。请求的资源上没有“Access-Control-Allow-Origin”标题。因此不允许Origin'http:// localhost:4200'访问。** –