【问题标题】:Angular 2 installed via CLI with ExpressAngular 2 通过 CLI 和 Express 安装
【发布时间】:2017-04-26 19:21:00
【问题描述】:

这是我的第一篇文章,如果我需要添加任何屏幕截图或代码 sn-ps,请告诉我。

我最近使用 Angular 2 CLI 创建了一个新应用。我能够通过模拟加载数据,但我正在努力解决如何连接到最终 API,同时仍然使用 CLI 提供的开发服务器对更改进行“实时”测试。

我目前拥有标准 CLI 端口 4200,以及 8181 的快速后端。

在遵循获取调用的角度文档时,我遇到了一个问题,因为我的 API 调用是针对 8181 端口的,并且出现浏览器控制台错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:4200' 因此不允许访问。

注意 - 已检查 Angular 2 cli with Express js,但似乎没有解决我的确切问题/问题

在连接到 API 的快速服务器时,利用开发服务器的正确方法是什么?提前非常感谢!

服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import { Sport } from './sport';

@Injectable()
export class SportService {
private sportsUrl = 'http://localhost:8181/sports'; //URL to web API
constructor(private http: Http) { }
getSports(): Promise<Sport[]> {
    return this.http.get(this.sportsUrl)
        .toPromise()
        .then(response => response.json().data as Sport[])
        .catch(this.handleError);}
private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
}
}

组件:

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Sport } from './sport';
import { SportService } from './sport.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [SportService]})

export class AppComponent implements OnInit {
ngOnInit(): void {
    this.getSports();}
    title = 'Olympics';
    constructor(private sportService: SportService) { }
sports: Sport[];
getSports(): void {
    this.sportService.getSports().then(sports => this.sports = sports);
}
}

【问题讨论】:

  • 为什么要展示 Angular 2 应用程序? CORS 标头必须由服务器添加,您应该研究如何在 Express 上允许 localhost:4200。

标签: angular express


【解决方案1】:

您需要配置代理。创建一个包含以下内容的文件 proxy-conf.json(假设您的 express 服务器中的端点包含/api):

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

按如下方式启动您的 Angular CLI 应用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 2018-10-06
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2017-05-02
    • 2017-02-14
    • 2017-01-30
    相关资源
    最近更新 更多