将 HTTP header 添加到 Angular HttpClient 不会发送 header,为什么?
Adding a HTTP header to the Angular HttpClient doesn't send the header, why?
这是我的代码:
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
并且数据存储在 'Request Payload' 但在我的服务器中没有收到 POST 值:
print_r($_POST);
Array
(
)
我认为错误来自于 POST 期间未设置的 header,我做错了什么?
新 HttpHeader
class 的实例是 不可变的 object。调用 class 方法将 return 一个新实例作为结果。所以基本上,您需要执行以下操作:
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'});
更新:添加多个 headers
let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');
或
const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
更新:为 HttpClient headers 和参数接受 object 映射
因为 5.0.0-beta.6 现在可以跳过 HttpHeaders
object 的创建,直接传递 object 映射作为参数。所以现在可以执行以下操作:
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
要添加多个参数或 headers 您可以执行以下操作:
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 })
在手册中 (https://angular.io/guide/http) 我读到:
HttpHeaders class 是不可变的,因此每个 set() returns 一个新实例并应用更改。
以下代码适用于 angular-4:
return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });
在您的 http 请求中像下面这样设置 http headers
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');
做了,当你意识到它们是不可变的时,这是有道理的。因此,创建了一个 header 后,您将无法添加。我没试过,但我怀疑
let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');
也可以。
在我的遗留应用程序中,原型 js 的 Array.from 与导致此问题的 angular 的 Array.from 冲突。我通过保存 angular 的 Array.from 版本并在原型加载后重新分配它来解决它。
Angular 8 HttpClient 服务示例 错误处理 和 自定义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)
)
}
....
....
查看完整的示例教程here
我和 Angular 8 在一起,唯一对我有用的是:
getCustomHeaders(): HttpHeaders {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Api-Key', 'xxx');
return headers;
}
首先,你需要用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;
});
我也在为此苦苦挣扎。我使用了一个拦截器,它捕获响应 headers,然后克隆 headers(因为 headers 是不可变的 objects),然后发送修改后的 headers。 https://angular.io/guide/http#intercepting-requests-and-responses
这是我的代码:
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
并且数据存储在 'Request Payload' 但在我的服务器中没有收到 POST 值:
print_r($_POST);
Array
(
)
我认为错误来自于 POST 期间未设置的 header,我做错了什么?
新 HttpHeader
class 的实例是 不可变的 object。调用 class 方法将 return 一个新实例作为结果。所以基本上,您需要执行以下操作:
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'});
更新:添加多个 headers
let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');
或
const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
更新:为 HttpClient headers 和参数接受 object 映射
因为 5.0.0-beta.6 现在可以跳过 HttpHeaders
object 的创建,直接传递 object 映射作为参数。所以现在可以执行以下操作:
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
要添加多个参数或 headers 您可以执行以下操作:
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 })
在手册中 (https://angular.io/guide/http) 我读到: HttpHeaders class 是不可变的,因此每个 set() returns 一个新实例并应用更改。
以下代码适用于 angular-4:
return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });
在您的 http 请求中像下面这样设置 http headers
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');
做了,当你意识到它们是不可变的时,这是有道理的。因此,创建了一个 header 后,您将无法添加。我没试过,但我怀疑
let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');
也可以。
在我的遗留应用程序中,原型 js 的 Array.from 与导致此问题的 angular 的 Array.from 冲突。我通过保存 angular 的 Array.from 版本并在原型加载后重新分配它来解决它。
Angular 8 HttpClient 服务示例 错误处理 和 自定义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)
)
}
....
....
查看完整的示例教程here
我和 Angular 8 在一起,唯一对我有用的是:
getCustomHeaders(): HttpHeaders {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Api-Key', 'xxx');
return headers;
}
首先,你需要用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;
});
我也在为此苦苦挣扎。我使用了一个拦截器,它捕获响应 headers,然后克隆 headers(因为 headers 是不可变的 objects),然后发送修改后的 headers。 https://angular.io/guide/http#intercepting-requests-and-responses