Frontend Development 9 min read

Introducing api-hook: A Lightweight Frontend Tool for API Interception and Mocking

The article presents api-hook, a lightweight React‑based frontend utility that enables developers to intercept, modify, and mock AJAX requests directly in the browser, offering ready‑to‑use, low‑cost solutions for comprehensive API testing and debugging.

Fulu Network R&D Team
Fulu Network R&D Team
Fulu Network R&D Team
Introducing api-hook: A Lightweight Frontend Tool for API Interception and Mocking

Preface

During web development, API integration and testing are critical, directly affecting product value. Various tools exist to simplify this work, but covering all success and failure scenarios can be costly. This article discusses a low‑cost approach to achieve comprehensive coverage using the api‑hook tool.

Current Situation

Common tools like Postman and Fiddler provide powerful features and plugins for API testing, including mock services, but they require time to set up. The article notes that while these tools can improve efficiency, they also demand a learning curve.

api‑hook Advantages

1. Ready‑to‑Use

api‑hook can be added to a project with minimal configuration, offering a visual, no‑learning‑cost interface for quickly modifying API responses.

2. Lightweight and Convenient

The tool is lightweight, requires no separate service, and lives as part of the page, allowing developers to control it like any other DOM element.

Tool Introduction

1) Demonstration

Feature Overview

[1] Switch area for API interception/mock, [2] Hide the api‑hook panel, [3] Show/hide panel toggle. API Interception

When the panel is visible and interception mode is active, all AJAX requests are captured before the page receives them. The currently edited request appears at the top with a zebra‑stripe animation; subsequent captured requests show a light‑blue background with a moving indicator. After editing, clicking “Confirm” switches the request to edit mode automatically.

The mock feature integrates mockjs; the template field must follow JSON syntax.

2) Environment Requirements

The tool is built with React and therefore requires a React‑based project. It intercepts all AJAX requests, so the project must use AJAX for API calls.

3) Usage

Install npm package npm install api-hook

Component Import Import the component in the project entry file.

import ApiHook from 'api-hook';
function App() {
return (
<div className="App">
<Main />
<ApiHook
autoFilter
defaultVisiable
allowOrigins={['http://localhost:3000']}
      />
</div>
);
}
...
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

4) Additional Notes

Supported Response Types Only text and json responses are handled. Types such as document , blob , or arraybuffer are ignored.

Component Props || Property || Description || Default || || autoFilter || Whether to intercept APIs by default || false || || defaultVisiable || Whether the tool panel is visible by default || false || || allowOrigins || Array of origins allowed to enable the tool || [] ||

R&D Introduction

1) Process Design

The tool offers two modes: API mock and API interception, each with slightly different internal flows.

In interception mode, responses are hijacked without altering the request flow, allowing status code and content edits via the UI. In mock mode, mockjs simulates data by proxying matching requests with a custom MockXMLHttpRequest.

2) XMLHttpRequest Proxy

To modify the default behavior of XMLHttpRequest, the project accesses a proxy object. Both interception and mock modes rewrite XMLHttpRequest using ajax‑hook and mockjs.

XMLHttpRequest = function () {
  var xhr = new window[realXhr];
  for (var attr in xhr) {
    var type = "";
    try { type = typeof xhr[attr]; } catch (e) {}
    if (type === "function") {
      // hookAjax methods of xhr, such as `open`, `send` ...
      this[attr] = hookFunction(attr);
    } else {
      Object.defineProperty(this, attr, {
        get: getterFactory(attr),
        set: setterFactory(attr),
        enumerable: true
      });
    }
  }
  // ...
};

mockjs mockjs stores the native XMLHttpRequest in window._XMLHttpRequest , creates a MockXMLHttpRequest that mimics the native behavior, and replaces window.XMLHttpRequest when Mock.mock(...) is called.

Proxy Object Switching Different modes use different proxy objects; switching between interception and mock requires resetting the native XMLHttpRequest and initializing the appropriate proxy.

// mock mode
registerMock() {
  unProxy(); // remove ajax‑hook proxy
  const { mockList } = this.state;
  mockList.forEach(({ url, template }) => {
    Mock.mock(url, template); // register mock
  });
}

// interception mode
unRegisterMock() {
  if (window._XMLHttpRequest) {
    window.XMLHttpRequest = window._XMLHttpRequest; // restore native
  }
  ajaxProxy(); // enable ajax‑hook proxy
}

Conclusion

The api‑hook tool is intended for frontend developers and testers, offering a convenient way to personalize API data. The current release includes basic features, with more to be added later. Repository: https://github.com/lanpangzi-zkg/api-hook . Feel free to star the project and discuss any issues.

frontendJavaScripttestingAJAXAPI mockingAPI Hook
Fulu Network R&D Team
Written by

Fulu Network R&D Team

Providing technical literature sharing for Fulu Holdings' tech elite, promoting its technologies through experience summaries, technology consolidation, and innovation sharing.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.