在 Angular 应用程序中使用 MVC 后端时,由于 URL 解析不正确,可能会出现返回 404 的情况。这可能是由于应用程序的路由设置或后端路由设置不正确。
解决此问题的方法是检查 URL 解析设置并确保它正确。还可以尝试使用 HttpInterceptors 进行拦截,并在请求中添加正确的 URL,如下所示:
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class APIInterceptor implements HttpInterceptor {
intercept(req: HttpRequesthttp://localhost:5000/api/${req.url}
});
return next.handle(apiReq);
}
}
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { AppComponent } from './app.component'; import { APIInterceptor } from './api.interceptor';
@NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], providers: [{ provide: HTTP_INTERCEPTORS, useClass: APIInterceptor, multi: true }], bootstrap: [AppComponent] }) export class AppModule { }
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template:
,
})
export class AppComponent implements OnInit {
response: any;
constructor(private http: HttpClient) {}
ngOnInit() {}
testAPI() { this.http.get('products').subscribe(response => { this.response = response; }); } }
这应该可以解决 Angular CLI 使用
上一篇:AngularCLI未强制使用默认的.onpush变更检测方式创建新组件。
下一篇:AngularCLI要求Node.js的最低版本为v14.20、v16.14或v18.10,但我只安装了v18.3版本。