Requirements: Intercept all XMLHttpRequest requests, and when the backend interface returns the login invalid status code, jump directly to the login interface and no longer pass it. It can also be used to request the addition of unified signatures, automatic protocol resolution, interface call statistics, etc.
Review:
While jQuery can intercept Ajax requests, it is limited to the caller using ajax methods in jQuery and cannot intercept requests using native XMLHttpRequest.Since the ajax request in jQuery is also an encapsulation of XMLHttpRequest, we can actually intercept XMLHttpRequest。
ajax-hook is a lightweight library for intercepting browser XMLHttpRequest objects, which can be used to preprocess requests, responses, and errors before the XMLHttpRequest object initiates a request, after receiving the response content, and when an error occurs. Ajax-hook is highly compatible and can run on any browser that supports ES5, as it does not rely on ES6 features.
Principle: ajax-hook customizes the methods and properties in XMLHttpRequest to override the global XMLHttpRequest object. A layer of proxy is wrapped for the XMLHttpRequest object.
Open Source Address:The hyperlink login is visible.
CDN address:The hyperlink login is visible.
proxy vs. hook
Both proxy() and hook() can be used to intercept global XMLHttpRequests. Their differences are:hook() has a fine interception granularity, can be specific to a certain method, attribute, or callback of the XMLHttpRequest object, but it is more troublesome to use, and many times, not only the business logic needs to be scattered in various callbacks, but also prone to errors. whereasproxy() has a high degree of abstraction, and the request context is built (the request information config can be obtained directly in each callback), which is simpler and more efficient to use.
Most of the time, weIt is recommended to use the proxy() method unless it does not meet your needs。
Try to add jQuery ajax request interception and proxy interception in ajax-hook, the code is as follows:
Try sending a get request using jQuery and you can see itBoth can be intercepted, as shown in the figure below:
Send a request using native XMLHttpRequest, discoverOnly ajax-hook can intercept, as shown in the figure below:
More uses of ajax-hook proxy:
Example:The hyperlink login is visible.
(End)
|