关于 Angular HTTP Interceptor 中 Request 和 Response 的 immutable 特性

简介: 关于 Angular HTTP Interceptor 中 Request 和 Response 的 immutable 特性

尽管拦截器能够修改请求和响应,但 HttpRequest 和 HttpResponse 实例属性为 readonly,这意味着其具有 immutability 特性。



这种特性是 Angular 框架有意为之的设计:应用程序可能会在一个 HTTP 请求成功完成之前,多次重试请求。换言之,这意味着 Interceptor chain 可以多次重新处理(re-process)相同的请求。 如果拦截器可以修改原始请求对象,则重试操作将从修改后的请求开始,而不是从原始请求开始,这会给应用程序的处理引入极大的不确定性。


因此,Angular Interceptor 处理上下文中的 HTTP 请求和响应的 immutability 特性,确保拦截器在每次尝试中处理的是相同的请求。


TypeScript 阻止开发人员设置 HttpRequest 对象中具有 readonly 的属性,看个具体的例子:


// Typescript disallows the following assignment because req.url is readonly
req.url = req.url.replace('http://', 'https://');


如果应用程序里必须更改 HTTP Request,请先克隆它并修改克隆,然后再将其传递给 next.handle()。 可以在一个步骤中克隆和修改请求,如以下示例所示:

// 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);



下面是 SAP Spartacus Interceptor 中使用 clone 方法去修改一个 HTTP Request 的具体例子:


[图片]


TypeScript 的 readonly 属性,并不能阻止 Request body 字段被 deep update.


下列代码能工作,然而却是一个糟糕的设计,原因如前所述:如果该 Interceptor 被重复调用,则每次调用会在前一次调用修改的 HTTP Request 的基础上再次进行修改,不断造成 Side Effect:


req.body.name = req.body.name.trim(); // bad idea!


Angular 推荐的做法依次是:


  • 对 Request body 进行 copy,并修改 copy 版本
  • 使用 HTTP Request 的 clone 方法,克隆请求对象。
  • 用修改后的 body copy 版本,替换克隆出来的 HTTP 请求的 body 字段。

伪代码如下:


// copy the body and trim whitespace from the name property
const newBody = { ...body, name: body.name.trim() };
// clone request and set its body
const newReq = req.clone({ body: newBody });
// send the cloned request to the next handler.
return next.handle(newReq);


相关文章
|
19天前
|
API 数据格式
8-20|https://gitlab.xx.com/api/v4/projects/4/trigger/pipeline Request failed状态码400
根据具体情况,逐步检查这些因素,找到引发400状态码的原因,并进行相应的修复。
24 0
|
6月前
|
JSON 小程序 前端开发
小程序踩坑-http://xxx.com 不在以下 request 合法域名列表中
小程序踩坑-http://xxx.com 不在以下 request 合法域名列表中
136 0
|
7月前
|
缓存 前端开发 JavaScript
为什么使用 CDN 需要 Angular 应用正确返回 HTTP 200 和 404 状态码
为什么使用 CDN 需要 Angular 应用正确返回 HTTP 200 和 404 状态码
66 0
|
4月前
|
缓存 前端开发 JavaScript
Angular Service Worker 在 PWA 应用 HTTP 交互中扮演的角色
Angular Service Worker 在 PWA 应用 HTTP 交互中扮演的角色
45 0
|
4月前
|
缓存 JavaScript 中间件
如何在 Angular 应用中发起 HTTP 302 redirect
如何在 Angular 应用中发起 HTTP 302 redirect
29 0
HTTP request以及response原理 request请求消息数据
HTTP request以及response原理 request请求消息数据
Http 实现用户登录(mysql+html+request)
Http 实现用户登录(mysql+html+request)
|
Web App开发 存储
Http服务器如何在HTTP response中传送二进制图片
要想知道如何传送这些二进制,先来点二进制文件的背景知识    —文件魔数 magic number: 操作系统的文件,其起始的几个字节的内容是固定的。
1235 0
|
2月前
|
前端开发
webpack如何设置devServer启动项目为https协议
webpack如何设置devServer启动项目为https协议
189 0