Programing

Angular HttpClient는 헤더를 보내지 않습니다.

crosscheck 2020. 6. 26. 08:15
반응형

Angular HttpClient는 헤더를 보내지 않습니다.


내 코드는 다음과 같습니다.

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

logIn(username: string, password: string) {
    const url = 'http://server.com/index.php';
    const body = JSON.stringify({username: username,
                                 password: password});
    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json; charset=utf-8');
    this.http.post(url, body, {headers: headers}).subscribe(
        (data) => {
            console.log(data);
        },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
                console.log('Client-side error occured.');
            } else {
                console.log('Server-side error occured.');
            }
        }
    );
}

그리고 여기 네트워크 디버그 :

Request Method:POST
Status Code:200 OK
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:46
Content-Type:text/plain

데이터가 '요청 페이로드'에 저장되었지만 내 서버에 POST 값이 수신되지 않았습니다.

print_r($_POST);
Array
(
)

POST 중에 설정되지 않은 헤더에서 오류가 발생했다고 생각합니다. 제가 잘못한 것은 무엇입니까?


HttpHeader클래스 의 인스턴스 변경할 수없는 객체입니다. 클래스 메소드를 호출하면 결과적으로 새 인스턴스가 리턴됩니다. 따라서 기본적으로 다음을 수행해야합니다.

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

또는

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

업데이트 : 여러 헤더 추가

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

또는

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

업데이트 : HttpClient 헤더 및 매개 변수에 대한 객체 맵 수락

5.0.0-beta.6 부터 HttpHeaders개체 생성을 건너 뛰고 개체 맵을 인수로 직접 전달할 수 있습니다. 이제 다음을 수행 할 수 있습니다.

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

배수 매개 변수 또는 헤더를 추가하려면 다음을 수행하십시오.

constructor(private _http: HttpClient) {}

//....

const url = `${environment.APP_API}/api/request`;

let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header

let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param 

return this._http.get<any[]>(url, { headers: headers, params: params })

set http headers like below in your http request

return this.http.get(url, { headers: new HttpHeaders({'Authorization': 'Bearer ' + token})
 });

I struggled with this for a long time. I am using Angular 6 and I found that

let headers = new HttpHeaders();
headers = headers.append('key', 'value');

did not work. But what did work was

let headers = new HttpHeaders().append('key', 'value');

did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect

let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');

would work too.


In the manual (https://angular.io/guide/http) I read: The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

The following code works for me with angular-4:

 return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });

In my legacy app Array.from of prototype js was conflicting with angular's Array.from that was causing this problem. I resolved it by saving angular's Array.from version and reassigning it after prototype load.


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<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

      ....
      ....

enter image description here

Check complete example tutorial here

참고URL : https://stackoverflow.com/questions/45286764/angular-httpclient-doesnt-send-header

반응형