Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

前端 未结 9 979
孤街浪徒
孤街浪徒 2020-11-22 05:45

Here is my code:

import { HttpClient, HttpErrorResponse, HttpHeaders } from \'@angular/common/http\';
9条回答
  •  再見小時候
    2020-11-22 06:25

    Angular 8 HttpClient Service example with Error Handling and Custom Header

        import { Injectable } from '@angular/core';
        import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
        import { Student } from '../model/student';
        import { Observable, throwError } from 'rxjs';
        import { retry, catchError } from 'rxjs/operators';
    
        @Injectable({
          providedIn: 'root'
        })
        export class ApiService {
    
          // API path
          base_path = 'http://localhost:3000/students';
    
          constructor(private http: HttpClient) { }
    
          // Http Options
          httpOptions = {
            headers: new HttpHeaders({
              'Content-Type': 'application/json'
            })
          }
    
          // Handle API errors
          handleError(error: HttpErrorResponse) {
            if (error.error instanceof ErrorEvent) {
              // A client-side or network error occurred. Handle it accordingly.
              console.error('An error occurred:', error.error.message);
            } else {
              // The backend returned an unsuccessful response code.
              // The response body may contain clues as to what went wrong,
              console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);
            }
            // return an observable with a user-facing error message
            return throwError(
              'Something bad happened; please try again later.');
          };
    
    
          // Create a new item
          createItem(item): Observable {
            return this.http
              .post(this.base_path, JSON.stringify(item), this.httpOptions)
              .pipe(
                retry(2),
                catchError(this.handleError)
              )
          }
    
          ....
          ....
    

    Check complete example tutorial here

提交回复
热议问题