【发布时间】:2021-03-12 10:36:48
【问题描述】:
刚刚开始学习 Angular 和 .Net api 的书。虽然复制所有内容但出现错误 在后端我有 .Net 核心 Api 和前端 Angular。我将天气应用程序(.net 标准应用程序)数据发送到 Angular 主机 4200,但出现错误,尽管后端服务器正常工作并显示天气应用程序数据没有任何错误,但在 Angular 端我收到以下错误。这里缺少什么。
运行时 ng serve --proxy-config proxy.config.json
错误:
*Failed to load resource: the server responded with a status of 504 (Gateway
Timeout)
*ERROR HttpErrorResponseerror: "Error occured while trying to
proxy to: localhost:4200/api/WeatherForecast"headers:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message:
"Http failure response for http://localhost:4200/api/WeatherForecast: 504
Gateway Timeout"name: "HttpErrorResponse"ok: falsestatus: 504statusText:
"Gateway Timeout"url: "http://localhost:4200/api/WeatherForecast"__proto__:
HttpResponseBase
defaultErrorLogger @ vendor.js:16907
以下是我的角度脚本:
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('/api/weatherForecast').subscribe(res => {
console.log(res);
});
}
}
app.component.ts:
import { Component } from '@angular/core';
import { ApiService } from './services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'accounting-app';
constructor(public apiService: ApiService){}
ngOnInit(){
this.apiService.getData();
}
}
proxy.config.json
{
"/api": {
"target": "http://localhost:5000",
"secure": false
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
【问题讨论】:
-
您在获取请求中没有传递正确的 URI this.http.get('/api/weatherForecast'),应该是 this.http.get('http(or) serverName/api/weatherForecast')
-
仍然收到同样的错误,尽管按照您的建议进行更新返回 this.http.get('localhost:4200/api/WeatherForecast').subscribe(res => { console.log(res);