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 。
响应拦截器在响应从服务器到达后立即被触发。请注意,响应拦截器以相反的注册顺序触发。
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
中:
关于javascript - 拦截HTTP请求和响应时,什么时候调用函数request、requestError、response、responseError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23916989/