首先,确保你的后端服务器正在运行,有正确的API地址,以及可以处理POST请求。
确保你的Angular应用程序与后端服务器的API地址相同。你可以在你的Angular服务中定义基URL,如下所示:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyService {
baseUrl = 'http://localhost:49540/api/';
constructor(private http: HttpClient) {}
postData(data: any) {
return this.http.post(this.baseUrl + 'create', data);
}
}
postData() {
const data = { name: 'John Doe', email: 'johndoe@example.com' };
return this.http.post(this.baseUrl + 'create', data);
}
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
console.log('404 Error: ', error.message);
}
return throwError(error);
})
);
}
}