如何从 HttpClient 拦截器获取 header 值/ body json 值
How to fetch a header value/ body json value from HttpClient interceptor
My Angular version: 6.0.3 and using HttpClient module
你好,在下面的代码中,我正在尝试获取 res.headers
和 res.body
以获取示例:
res.headers.status
, res.body.id
如果可能:
但每当我尝试登录控制台时。它会产生错误。
使用语法 res['headers']
,res['body']
可以在控制台中打印出来。但无法进一步提取。
HttpsInterceptor Class:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap, finalize } from "rxjs/operators";
//import { MessageService } from '../../message.service';
export class HttpsInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const started = Date.now();
let ok: string;
let res: any;
console.log(req.headers.keys());
// return next.handle(req);
// clone request and replace 'http://' with 'https://' at the same time
const secureReq = req.clone({
url: req.url.replace('http://', 'https://')
});
// send the cloned, "secure" request to the next handler.
return next.handle(secureReq).pipe(
tap(
// Succeeds when there is a response; ignore other events
(event) => {
ok = event instanceof HttpResponse ? 'succeeded' : ''
res = event;
console.log("Response:", res);
/* NOT WORKING */ console.log("res: headers", res.headers);
/* NOT WORKING */ console.log("res: body", res.body);
},
// Operation failed; error is an HttpErrorResponse
error => ok = 'failed'),
finalize(() => {
const elapsed = Date.now() - started;
const msg = `${req.method} "${req.urlWithParams}"
${ok} in ${elapsed} ms.`;
//this.messenger.add(msg);
console.log(msg);
})
);
}
}
控制台日志:
Response:
{…}
body: {…}
address: "76, Shilpgram tenaments, Soma talav, Dabhoi ring road, Vadodara, Gujarati, India - 390001"
email: "cust@ngapp.com"
fullname: "Amit Shah"
id: 1
password: "cust1234"
phone: "+91-123456789"
<prototype>: Object { … }
headers: {…}
lazyInit: function lazyInit()
lazyUpdate: null
normalizedNames: Map(0)
<prototype>: Object { has: has()
, get: get(), keys: keys()
, … }
ok: true
status: 200
statusText: "OK"
type: 4
url: "https://demo1601932.mockable.io/customer/get/1"
<prototype>: Object { constructor: HttpResponse()
, clone: clone() }
实际上,next.handle(...)
returns Observable<HttpEvent>
。
这个HttpEvent
是5种。
type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;
所以,当它是HttpResponse
类型时,你必须读取响应头。我刚刚在您的代码中添加了一个 if
块。
return next.handle(secureReq)
.pipe(
tap((event) => {
ok = event instanceof HttpResponse ? 'succeeded' : '';
if(ok) {
res = event;
console.log("Response:", res);
console.log("res: headers", res.headers);
console.log("res: body", res.body);
}
})
);
My Angular version: 6.0.3 and using HttpClient module
你好,在下面的代码中,我正在尝试获取 res.headers
和 res.body
以获取示例:
res.headers.status
, res.body.id
如果可能:
但每当我尝试登录控制台时。它会产生错误。
使用语法 res['headers']
,res['body']
可以在控制台中打印出来。但无法进一步提取。
HttpsInterceptor Class:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap, finalize } from "rxjs/operators";
//import { MessageService } from '../../message.service';
export class HttpsInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const started = Date.now();
let ok: string;
let res: any;
console.log(req.headers.keys());
// return next.handle(req);
// clone request and replace 'http://' with 'https://' at the same time
const secureReq = req.clone({
url: req.url.replace('http://', 'https://')
});
// send the cloned, "secure" request to the next handler.
return next.handle(secureReq).pipe(
tap(
// Succeeds when there is a response; ignore other events
(event) => {
ok = event instanceof HttpResponse ? 'succeeded' : ''
res = event;
console.log("Response:", res);
/* NOT WORKING */ console.log("res: headers", res.headers);
/* NOT WORKING */ console.log("res: body", res.body);
},
// Operation failed; error is an HttpErrorResponse
error => ok = 'failed'),
finalize(() => {
const elapsed = Date.now() - started;
const msg = `${req.method} "${req.urlWithParams}"
${ok} in ${elapsed} ms.`;
//this.messenger.add(msg);
console.log(msg);
})
);
}
}
控制台日志:
Response:
{…}
body: {…}
address: "76, Shilpgram tenaments, Soma talav, Dabhoi ring road, Vadodara, Gujarati, India - 390001"
email: "cust@ngapp.com"
fullname: "Amit Shah"
id: 1
password: "cust1234"
phone: "+91-123456789"
<prototype>: Object { … }
headers: {…}
lazyInit: function lazyInit()
lazyUpdate: null
normalizedNames: Map(0)
<prototype>: Object { has: has()
, get: get(), keys: keys()
, … }
ok: true
status: 200
statusText: "OK"
type: 4
url: "https://demo1601932.mockable.io/customer/get/1"
<prototype>: Object { constructor: HttpResponse()
, clone: clone() }
实际上,next.handle(...)
returns Observable<HttpEvent>
。
这个HttpEvent
是5种。
type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;
所以,当它是HttpResponse
类型时,你必须读取响应头。我刚刚在您的代码中添加了一个 if
块。
return next.handle(secureReq)
.pipe(
tap((event) => {
ok = event instanceof HttpResponse ? 'succeeded' : '';
if(ok) {
res = event;
console.log("Response:", res);
console.log("res: headers", res.headers);
console.log("res: body", res.body);
}
})
);