这是我的代码:

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期间没有设置头,我做错了什么?


当前回答

带有错误处理和自定义报头的Angular 8 HttpClient服务示例

    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)
          )
      }

      ....
      ....

点击这里查看完整的示例教程

其他回答

我也在和这个斗争。我使用了一个拦截器,它捕获响应头,然后克隆头(因为头是不可变的对象),然后发送修改后的头。https://angular.io/guide/http#intercepting-requests-and-responses

在我的遗留应用中,prototype js的Array.from与angular的Array.from冲突导致了这个问题。我通过保存angular的Array.from version并在原型加载后重新分配它来解决这个问题。

首先,您需要使用HttpClient添加HttpHeaders

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

构造函数应该如下所示。

constructor(private http: HttpClient) { }

然后你可以这样用

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

在HTTP请求中像下面这样设置HTTP报头

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

我为此挣扎了很长一段时间。我使用的是Angular 6,我发现了这一点

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

没有工作。但真正起作用的是

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

当你意识到它们是不可变的时候,这就说得通了。因此,创建了一个标题,你不能再添加它。我没试过,但我猜

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

也会起作用。