gpt4 book ai didi

javascript - 在拦截 HTTP 请求和响应时,什么时候调用函数 request、requestError、response、responseError?

转载 作者:行者123 更新时间:2023-11-29 19:39:25 25 4
gpt4 key购买 nike

documentation提到您可以为拦截器定义 4 个函数,它说:

There are two kinds of interceptors (and two kinds of rejection interceptors):

request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.

requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

我只定义了一个拦截器。我注意到,如果响应 HTTP 代码为 403,则会调用 responseError 函数。我不确定还有什么可能触发它。 文档中的什么地方是否说明了这 4 个函数何时被调用?请引用任何有信誉的来源。

它说:

"... when a previous interceptor threw an error or resolved with a rejection"

它什么时候抛出错误或者它如何通过拒绝解决?我需要对这部分进行更多详细说明。

最佳答案

好吧,如你所料......

request 拦截器在将请求发送到服务器之前触发(当然在使用 transformRequest 函数转换数据之前)。

requestError 拦截器在出现请求错误时被触发,即如果之前的任何请求拦截器抛出错误或返回一个被拒绝的 promise 。

response 拦截器在响应从服务器到达时立即触发。请注意,响应拦截器以相反的注册顺序触发。

responseError 当 HTTP 状态代码指示错误(即它不是重定向且超出 [200-299] 范围)或任何先前的响应拦截器抛出时,将触发拦截器错误或返回被拒绝的 promise 。


关键是上述任何方法都可以返回“正常”对象/基元或将以适当值解析的 promise 。在后一种情况下,队列中的下一个拦截器将等待返回的 promise 被解决或拒绝。

在此上下文中,抛出错误是指普通的旧 JavaScript 错误。例如。尝试访问不存在的方法 ( myObj.methodThatDoesNotExit() ) 或显式引发异常 ( throw Error() )。

可以通过返回 $q.reject(someObj) 来创建被拒绝的 promise 或调用 .reject(reason)在返回 promise 的延迟对象上。


如文档所述,重要的是“在开始创建拦截器之前,一定要理解 $q and deferred/promise APIs


处理拦截器的源代码的相关部分(v1.2 分支 - 当前版本 1.2.16)在 ng/http.js 中:

line 127 - line 155
<强> line 685
- line 724

关于javascript - 在拦截 HTTP 请求和响应时,什么时候调用函数 request、requestError、response、responseError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23916989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com