简体   繁体   English

Angular2 HTTP请求提供者

[英]Angular2 HTTP Request Providers

I want to make connection between my angular app and my REST API. 我想在我的角度应用程序和REST API之间建立连接。 Here it returns JSON http://is.njn.mvm.bg/check . 在这里,它返回JSON http://is.njn.mvm.bg/check So my question is which providers do I need because I include in app.module, but it still doesn't work. 所以我的问题是,我需要哪些提供程序,因为我将其包含在app.module中,但仍然无法正常工作。 import { HttpModule} from '@angular/http';
I am using Angular2 HTTP tutorial 我正在使用Angular2 HTTP教程

  private heroesUrl = 'http://is.njn.mvm.bg/check';  // URL to web API
  constructor (private http: Http) {}
  getHeroes (): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  } 

I am getting XMLHttpRequest cannot load http://localhost:8000/da. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 我收到XMLHttpRequest cannot load http://localhost:8000/da. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. XMLHttpRequest cannot load http://localhost:8000/da. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

you are using the http request wrong. 您正在使用http请求错误。 plz use following code. 请使用以下代码。

app.component.ts app.component.ts

 //our root app component import { Component } from '@angular/core' import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'root', template: ` <div> {{people}} {{ err}} </div> ` }) export class App { people; err; constructor(http:Http) { http.get('http://is.njn.mvm.bg/check').map(res => res.text()).subscribe(people => this.people = people,err=>this.err = err); // Subscribe to the observable to get the parsed people object and attach it to the // component } } 

Also remember Follow error occur in your console: Access-control-allow-origin 还请记住您的控制台中发生跟随错误: Access-control-allow-origin

For remove this error see: 

chrome extension for access control chrome扩展访问控制

You need to put header parameter "Access-Control-Allow-Origin" in the server's HTTP response. 您需要在服务器的HTTP响应中放置标头参数“ Access-Control-Allow-Origin”。 You can't make this work from the client side only. 您不能仅从客户端进行此工作。 I also had the same issue when trying to grab data from my Java JSON REST server. 当尝试从Java JSON REST服务器获取数据时,我也遇到了同样的问题。 I am not sure what you use server side, but in Java it looks something like this: 我不确定您在服务器端使用什么,但是在Java中看起来像这样:

return Response.ok() //200
            .header("Access-Control-Allow-Origin", "*");

For information on this error (CORS), see this: 有关此错误(CORS)的信息,请参见:

How does Access-Control-Allow-Origin header work? Access-Control-Allow-Origin标头如何工作?

You also need to add it to imports of @NgModule 您还需要将其添加到@NgModule imports

@NgModule({
  imports: [BrowserModule, HttpModule]
  ...
})

You module code will be like below: 您的模块代码如下所示:

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    {provide: APP_BASE_HREF, useValue: '/'},
  ],
  bootstrap: [AppComponent]
})

export class AppModule {

}

you service code need to similar to this 您的服务代码需要与此类似

  constructor(private http: Http) {
  }

  getCountriesByRegion(region: string) {
    return this.http.get(this.countries_endpoint_url + region).map(res => res.json());
  }


//you can also do like this
  getHeroes(): Observable<any[]> {
    return this.http.get(this.heroesUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

You have the Angular app that's served by the server running on port 3000, but this app tries to make HTTP calls to the server running on another port 8000. 您具有在端口3000上运行的服务器提供的Angular应用程序,但是此应用程序尝试对在另一个端口8000上运行的服务器进行HTTP调用。

You have two options: 1. Deploy your Angular app under the server that runs on port 8000, in which case your Angular app will hit the same port it was served from. 您有两个选择:1.将Angular应用程序部署在端口8000上运行的服务器下,在这种情况下,您的Angular应用程序将访问与其提供服务的端口相同的端口。 2. Configure a proxy on the server that runs on port 3000 to allow access to port 8000. 2.在运行于端口3000的服务器上配置代理,以允许访问端口8000。

For the second scenario, if you use Angular CLI with your project, create a file proxy-conf.json, for example: 对于第二种情况,如果在项目中使用Angular CLI,则创建文件proxy-conf.json,例如:

{
  "/api": {
    "target": "http://localhost:8000",
    "secure": false
  }
}

Then sevre your Anglar app like this: 然后像这样将您的Anglar应用程序设置为:

ng serve --proxy-config proxy-conf.json ng serve --proxy-config proxy-conf.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM