Designing a Fetch client with Express-style middleware

May 6, 2025

A user opens the asset list and the server returns 401: their credentials have expired. Should the page ask them to sign in, or refresh the access token and retry silently? Opening the activity log would need almost identical handling, apart from the URL. Why should every page know how to do this?

Fetch and XMLHttpRequest (XHR) can both request the asset list. Fetch supports await for the response; XHR can also report bytes sent during uploads. 12 I wanted an upload-progress callback for a progress bar, so on May 4 I read MDN on XMLHttpRequest.upload and explored libraries wrapping both APIs. Axios already accepts onUploadProgress on uploads. Myxios and my later Express Http Client could send files using Fetch, but Express Http Client 0.3.6 still lacked this callback. 345

I also looked at WebSocket. For live inventory updates, a server can push changes and the page can send messages over the same connection. 6 Existing HTTP clients did not generally route WebSocket messages through HTTP interceptors. Axios offered upload progress but no built-in WebSocket client. 3 I saw little demand in my library for one interceptor chain handling both protocols, so I omitted WebSocket support.

Back to the asset list. A page could look like this:

const response = await fetch("/api/assets");
if (response.ok) {
    const assets = await response.json();
    // 把资产显示在页面上
}

fetch sends the request. await waits for the response before continuing. A 401 still gives fetch a Response object with status equal to 401 and ok equal to false. Catching network exceptions alone cannot handle expired sessions. We need somewhere to inspect the status before the page reads it and, if needed, return a retried response. 1

Is one shared function enough?

If every page needs only one auth rule, I would start with fetchWithAuth: add the header before sending, inspect status afterward and return a Response. Change the refresh endpoint once. A second requirement introduces composition: one client needs timing and another just authentication. Logging before retry records 401; after retry it may record 200. Callers need to choose the steps and their order.

An interceptor is a function the client invokes automatically before sending or after receiving. In designing an authentication interface I cared what its author had to learn and what control they retained.

PatternHow would the authentication author use it?
Axios instance and interceptorsMake a shared client with axios.create(). Add the auth header in a request interceptor and return config. Register response handlers using instance.interceptors.response.use(成功回调, 失败回调) and pass results onward by returning them. 7
Angular functional interceptorsClone the request with req.clone(...) to add a header, then return next(newReq). The interceptor explicitly passes the new request and returns an Observable HTTP event stream upstream. It can observe the final response on that stream. 8
Express server middlewareStore user information on req.user and call next(). The router passes the same req and res to the next matching middleware. return next() is common; return exits the current function. 910

With Axios, how do I resend the specific failed asset or log request? Its default configuration sends 401 to a response interceptor’s rejection callback. error.response.status identifies the status, and error.config retains URL, method and other configuration. After refreshing and updating the header, return instance(error.config) delivers the retry result to the original caller. 7

Two tutorials clarified different problems. Veljko Ilić stored a _retry flag on the request configuration to stop another 401 on the retried request from refreshing forever. 11 Francisco Mendes considered concurrent requests: if assets and logs both return 401, separate request flags cannot coordinate. He extracted refresh into a shared function with a ten-second result cache so several calls could share one refresh. 12

My Fetch client receives 401 as a normal Response in its response chain. The handler checks data.response.status and retrieves the original from data.request. This is a Fetch Request whose url, method and headers record destination, HTTP method and headers. 13 Both designs hide retries in shared code, but the location of the original request and the way back to the caller differ. 114

After functional interceptors, why choose a cursor?

In Myxios I liked chaining response functions. Each took the accumulated result and returned its contribution, making layers independently testable. But a user adding one log line still had to understand what came in and how the return value merged into the next step. For Express Http Client, I wanted someone familiar with fetch, if and await to read a single function and understand what it did. 1516

People arrive at frontend development by many paths. Someone can write good pages and diagnose a network request without using higher-order functions to compose asynchronous operations. Understanding composition just to add an auth header seemed costly. Start with an ordinary handler, then consider order when adding a second.

In hindsight Angular and Express both influenced the API. Developers recognize next as handing work to the next layer. The name conveys familiarity; the library still defines its parameters and return value. I chose the Express convention: write the revised request to data.request, then call next(). To examine the response, register a response interceptor and read data.response. 1710518

I also wanted Express backends to use the client to call other services. The browser requests assets from Express, and Express as a client queries inventory. The outbound middleware adds its service header, calls next() and later logs inventory’s status. The two next() calls belong to separate chains but share a familiar handoff.

How does a page use a function it never explicitly calls?

Suppose assets and activity logs both need the current access token. This example uses the 0.3.6 interface. The application provides readToken() to read the signed-in user’s current token. 5

import { httpClient } from "express-http-client";

function addAuthHeader(data, next) {
    const headers = new Headers(data.request.headers);
    headers.set("Authorization", "Bearer " + readToken());
    data.request = new Request(data.request, { headers });
    next();
}

const setup = httpClient();
setup.addRequestInterceptor(addAuthHeader);
const api = setup.create("https://example.com");

const response = await api.send("/api/assets");

Registration through addRequestInterceptor(addAuthHeader) places the function itself in an array. It sends no request and reads no token. Each send() later executes addAuthHeader for that request. A call to api.send("/api/logs") runs the same function using the token current at that moment. 5

Why create a client with setup.create()? On May 11 I read about JavaScript private methods and MDN’s emulated private constructor. Two questions were involved. First, who can create an instance? JavaScript has no native private constructor syntax. MDN’s static factory sets a private flag before new, and the constructor throws if the flag is missing. I exposed a factory as the package entry point. It collects the two interceptor sets and uses a normal constructor. 195

Second, which methods do pages need afterward? The May 12 prototype exposed send() for requests. It stored the two arrays in #requestInterceptors and #responseInterceptors, running #executeRequestInterceptors() and #executeResponseInterceptors() before and after sending. # restricts direct external access, not mutation of the array contents. In 0.3.6 I moved chain execution to Core.js while keeping private fields in the instance. Page code calling api.send(...) did not change. 205

Why assign the new object to data.request? I had logged a new Request with an auth header, yet the server received a request without one. Starting with let request = data.request and reassigning only local request changes that variable’s reference. Outer code still reads the old object from data.request. Share a plain object data and agree to replace requests by updating its request property; the next step then sees the same change. 2120

How does next() know which function comes next?

Express and Angular let the current layer decide when to pass down a request. Middleware next recalls an iterator, but iterator.next() returns an item with value and done, whereas middleware next runs the next layer. The two frameworks implement the handoff differently. 22

How could authentication holding only next know to run logging next? Reading Express, I found it augments Node requests and then calls this.router.handle(req, res, done) from app.handle. Following require('router') in application.js revealed that Express 5 delegates selection and execution of the next middleware to an independent npm package, router. 23

Its npm page led to pillarjs/router, where I read lib/route.js, index.js and lib/layer.js. I wanted to borrow the transition between layers. 105

StepExpress routerMy client
What is registered?router.use wraps path and handler in a Layer and adds it to stack in order.Store the function directly in the request or response array. The caller has already selected the client and phase.
Who remembers position?Router.handle creates a per-call idx starting at zero. next takes stack[idx++] and matches paths. Within a route, Route.dispatch similarly matches by HTTP method.Each dispatcher creates a per-call index. The initial next() starts the chain; interceptors[index++] selects the current function and advances.
Who invokes business code?Layer.handleRequest takes the function in this.handle and calls fn(req, res, next). The handler can return control with next.Invoke interceptor(data, next, end) directly. The current layer can wait for asynchronous work and then call the same next().

I borrowed the dispatch algorithm: store in registration order, advance the cursor when taking the current item, and pass the same next to each handler. Express also processes path parameters. In /assets/:id, a registered handler for id runs before the route handler. 24 By the time my client calls send() it already knows the interceptor array, so it can call the next entry directly. 5

Angular functional interceptors use return next(req). Angular 17 uses reduceRight to compose from the end. First wrap the sending backend in logging, then wrap logging in authentication. Logging is assembled first, but authentication runs first because it is outermost. Its next already represents logging and everything beyond. Later requests can reuse the composed function. The class-based form delegates via next.handle(req). 17

How can logging associate the final status with the request URL? Angular’s response-stream callback closes over the request object. The callback still sees that invocation’s req and can log req.url with the final status. 8

I described the design choice this way:

“change this to the imperative way using next and stack cursor like express middleware”18

The normal path of the request dispatcher in Core.js reduces to the code below. The Promise represents the Request the whole chain will eventually supply; its resolve lets the waiting code continue. The implementation also handles exceptions and next(error). 5

function runRequestChain(data, steps) {
    let index = 0;
    return new Promise(resolve => {
        function end() {
            resolve(data.request);
        }
        function next() {
            const step = steps[index++];
            if (step === undefined) {
                end();
                return;
            }
            step(data, next, end);
        }
        next();
    });
}

With [addAuthHeader, logRequest], the final line first calls next(). steps[index++] takes authentication at position zero and advances index to one. Authentication adds a header and calls the same next; logging at position one sees the new request. Logging calls again and there is nothing at position two, so end() returns the final Request. The next send() starts a fresh dispatcher with index = 0. 5

A cursor makes registration order the order visible in the debugger. Our asset system once put logger() before the 401 handler. A logged 401 and a 200 at the page were both correct: the log saw the original before authentication retried and replaced it. Register logging later to observe the retry result. Break on interceptors[index++] in the response dispatcher, inspect the next handler and check its data.response.status. I find this easy to troubleshoot from the registration list. 51425

Java Servlet filters illustrate a similar convention. A filter calls chain.doFilter(request, response) when ready, and the container finds the next layer. The visible handoff does not prove that the container internally uses the same cursor. 26

Why not a simple for loop over all handlers? Under a return-means-finished contract every async handler must return its Promise. I wanted middleware to start asynchronous work, return immediately and release the chain through next() in a later callback. The chain signals completion when next reaches the end or a handler explicitly calls end. If a handler returns without either, the page’s await api.send(...) keeps waiting. 185

Who actually sends the request after the chain finishes?

The inner dispatcher selects handlers. The outer HttpClient.send() performs the send. Here is the normal data path, omitting timing and error handling, which explains how responses stay paired with requests. 5

const data = { request: new Request(url, options), store: new Map() };
const request = await executeRequestInterceptors(data, requestInterceptors);
data.response = await fetch(request);
return await executeResponseInterceptors(data, responseInterceptors);

All of these lines share one data. The request chain returns finalized data.request for outer fetch. Response handlers then have both the outgoing request and incoming response. store is a fresh key-value store per invocation through which layers can exchange extra information independently of concurrent calls. 5

Angular’s HttpRequest.context similarly carries information for interceptors without sending it to the backend. To skip caching on a request, a page can set the cache switch (an HttpContextToken) in context to false. The interceptor sees it; the server receives no extra switch. 8

How do POST forms and files reach Fetch?

Axios examples pass an object as the second argument to axios.post(url, data). I also read URL-encoded and multipart examples but did not originally test my own library. new Request(url, options) accepts Fetch body directly. 27 While editing I sent each type with both 0.3.6 api.send() and the standalone request(). A local server parsed the following results. 28

ContentCaller suppliesServer receives
JSONbody: JSON.stringify(data) and a header specifying Content-Type: application/jsonChinese fields and an array
URL-encoded formbody: new URLSearchParams(fields), where fields is a list of key-value pairsA Chinese value with spaces and two values for a repeated key
Fields and a filebody: form, where form is a FormData with both text and file entriesText, filename and file content

If the page already has file from a file input, upload takes these three steps. Let Fetch generate the multipart Content-Type including the boundary so the server parses fields with the same separator. 29

const form = new FormData();
form.append("attachment", file);
await api.send("/api/attachments", { method: "POST", body: form });

Why handle request and response errors separately?

I consulted Express’s error handling guide. A server has already received the request. After ordinary middleware calls next(err), Express skips normal handlers to find a four-argument error handler with res, which decides status and body. 3010 In a client, before sending, the decision is whether to send at all. After receiving, the question is what the page gets and whether it can use normal Fetch checks. I recall this as the reason for retaining next but separating error paths.

Suppose inventory requires signed requests. Once signing succeeds and remaining request middleware is unnecessary, end() returns the current Request and the outer fetch(request) proceeds. On signing failure, next(error) rejects the chain. send() throws before later handlers or fetch run. The caller can inspect the signing error in try/catch and decide whether to retry, preserving the cause and avoiding a predictably invalid call. 5

On the response side, pages already use response.ok to decide whether data is usable. When an asset request returns 401, the auth interceptor attempts a refresh. If it throws, it clears login state, redirects and calls next(error). Version 0.3.6 gives the caller a client-generated 424 Response with ok set to false. That answers the page’s usability question, although a 424 alone cannot distinguish a server status from client processing failure. 514

Two paths generate 424. When fetch throws, send() stores 424 in data.response before the response chain, so logging sees that status. When an interceptor calls next(error), the dispatcher delivers 424 directly to the awaiting caller. A subsequent layer may still execute, but data.response is unchanged. Thus logging may record the original 401 while the page reads 424. One number describes the server’s original answer, the other the client’s final delivery. 31525

The built-in mockResponse() runs in the response chain. Receiving mock data does not mean the server did not execute the operation. See mocking API responses on the frontend with interceptors for examples of both interception points. 525

After refreshing a token, how is the original request resent?

In the real ExpressHttpHandler.js I put retries in a response interceptor. The example is restricted to a GET with no request body. For clarity, refreshAccessToken() calls a separate refresh endpoint and saves and returns the new token, or an empty result on failure; returnToLogin() clears the session and returns to sign-in. Register the layer before setup.create(...) in the earlier example. 14

setup.addResponseInterceptor(async (data, next) => {
    if (data.response.status === 401) {
        const token = await refreshAccessToken();
        if (token) {
            const headers = new Headers(data.request.headers);
            headers.set("Authorization", "Bearer " + token);
            const retry = new Request(data.request, { headers });
            data.response = await fetch(retry);
        } else {
            returnToLogin();
        }
    }
    next();
});

Suppose the first asset lookup gets 401 and the second gets 200. The second fetch builds a new Request from the original and queries the same asset. Calling Fetch directly avoids re-entering this client’s 401 chain. Assigning data.response = … delivers the second 200 to later middleware and the page. If we only await fetch(retry) without saving it, the retry still succeeds but the page sees the first 401. Uploads and other requests with bodies need a reusable body arranged before the first send. See the request body example in the Fetch debugging article. 141

When would I choose this over Axios?

Pages already using if (response.ok) and await response.json() can switch to api.send() for shared auth without changing the response handling. Middleware also sees Fetch Request and Response. Axios 1.7.0 can use Fetch underneath but gives callers an Axios response, typically read via response.data. An Axios-based project can likewise save changes by staying with Axios. 57

Registration order differs. To add headers before signing them, my client registers the header handler before the signer. Both chains execute first-registered first. Axios 1.7.0 prepends request interceptors and appends response interceptors, so register signing first and header addition second there. Both can sign correctly. Mine lets maintainers read top to bottom to verify which headers exist at signing. 532

I described my intent in the README as giving users more control with minimal features. 16 In practice, a page reads assets; the library supplies requests, responses and ordering; the application decides when to refresh and which sign-in page to show. Version 0.3.6 uses the environment’s Fetch with no runtime dependencies. The README put its production build at about 3.7 kB or 1.3 kB gzipped. Projects relying on Axios transformations or Angular event streams have reasons to keep them. This design lets people already using Fetch add behavior one layer at a time. 331678

Using the client as an AI gateway

Send an app’s model requests through the same client to count calls and measure time to response headers. OpenAI’s official JavaScript SDK v4.90.0, released March 2025, already offered a custom fetch option, described as a custom fetch implementation. 34 Given the Express Http Client instance api, the integration point looks like this:

const client = new OpenAI({
  fetch: (input, init) => api.send(input, init),
});

The SDK builds model requests. Request middleware records start time; response middleware records duration and status, then returns the Response for the SDK to consume. SDK retries can be counted individually. To estimate cost, read token usage from model results and apply the relevant model price. This uses Fetch’s input and response contract. Version 0.3.6 turns network exceptions into 424 responses, which can change the SDK’s network-error behavior. 531

A wrapper around globalThis.fetch can time every call through the environment’s global entry point by saving and invoking the original function. Using my library globally would require changing its transport to call that saved function, otherwise send() would call itself recursively. For the historical OpenAI SDK, passing a custom function to the instance was more dependable: v4.90.0 on Node defaulted to its own node-fetch. Vercel AI SDK’s OpenAI package offers a similar instance option, createOpenAI({ fetch: myFetch }). 53435

The Fetch contract saves an adapter. Axios 1.7.0 can instrument requests via interceptors but an Axios instance cannot simply be supplied as the SDK’s fetch. Even with its Fetch adapter it returns an Axios response with data, status and other fields. Reusing it here would require converting configuration, providing a Fetch Response and handling non-2xx and streaming behavior. 36

References

Footnotes

  1. MDN contributors. (n.d.). Using the Fetch API [Making a request、Handling the response]. MDN Web Docs. Retrieved April 25, 2025, from Using the Fetch API。另见 MDN contributors. (n.d.). Fetch API. MDN Web Docs. Retrieved May 4, 2025, from Fetch API。 ↩ ↩2 ↩3 ↩4

  2. MDN contributors. (n.d.). XMLHttpRequest;XMLHttpRequest: upload property. MDN Web Docs. Retrieved May 4, 2025, from XMLHttpRequest and XMLHttpRequest.upload。 ↩

  3. Axios contributors. (n.d.). Axios [v1.7.0]. GitHub. 上传进度回调的用法、内置的 HTTP、XHR 和 Fetch 适配器。 ↩ ↩2

  4. Cai, B. [S2thend]. (2025, April 25). Myxios [请求入口,提交 ab60247]. GitHub. 两个请求方法都把 URL 和选项传给 fetch。 ↩

  5. Cai, B. [S2thend]. (2025, May 13). Express Http Client [0.3.6,提交 7357757]. GitHub. HttpClientFactory.js 中的注册和创建、Core.js 中两条链的调度、HttpClient.js 中的 send。正文代码按此版本改写。 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12 ↩13 ↩14 ↩15 ↩16 ↩17 ↩18 ↩19 ↩20 ↩21 ↩22

  6. MDN contributors. (n.d.). WebSocket API (WebSockets) [开头对双向通信的说明]. MDN Web Docs. Retrieved May 4, 2025, from WebSocket API。 ↩

  7. Axios contributors. (n.d.). Axios [v1.7.0 历史版本]. GitHub. 创建实例、注册请求与响应拦截器、处理错误与 validateStatus 配置、状态检查失败时把请求配置和响应放进 AxiosError。2025 年 4 月 24–25 日及 5 月 11 日的访问记录包括 Axios 实例与拦截器文档;当时访问的拦截器地址是 axios-http.com/docs/interceptors。现行文档见 Interceptors,正文的执行顺序以 v1.7.0 源码为准。 ↩ ↩2 ↩3 ↩4

  8. Angular team. (n.d.). Intercepting requests and responses. Angular. Retrieved May 6 and May 11, 2025. Defining an interceptor 说明 next 的参数和返回值。Intercepting response events 示例后的 Tip 解释闭包如何保留原请求。Request and response metadata 第 1 段说明元数据的用途。缓存开关示例见 Defining context tokens、Reading the token in an interceptor 和 Setting context tokens when making a request。 ↩ ↩2 ↩3 ↩4

  9. Express contributors. (n.d.). Using middleware [Guide,开头的中间件职责与 next() 说明]. Express. Retrieved April 25, 2025, from Using middleware。另见 Express contributors. (n.d.). Writing middleware for use in Express apps. Express. Retrieved May 6, 2025, from 中间件如何修改请求对象并用 next 放行。 ↩

  10. PillarJS contributors. (n.d.). router [v2.2.0]. GitHub. Router.use 创建 Layer 并入栈、Router.handle 的游标与路径匹配、Route.dispatch 按方法选层并传入 next、路由器在普通处理与错误处理之间分派、Layer 调用普通处理函数和错误处理函数。原分支链接为 index.js L188、L237 和 layer.js L106。分支行号会随修改移动,正文按 v2.2.0 说明。 ↩ ↩2 ↩3 ↩4

  11. Ilić, V. [@velja]. (2024, February 8). Token Refresh with Axios Interceptors for a Seamless Authentication Experience. Medium. Step 3,检查原请求的重试标记。 ↩

  12. Mendes, F. [franciscomendes10866]. (2022, June 18). How to Refresh Json Web Tokens (JWT) using Axios Interceptors. DEV Community. Configure Axios instances,封装刷新函数与设置缓存时间。 ↩

  13. MDN contributors. (n.d.). Request. MDN Web Docs. Retrieved April 25, 2025, from Request。属性列表见 Instance properties。 ↩

  14. CaiBorui. (2025, May 21). Add support for express http handler [资产管理项目本地 Git 提交 54933d55b9382d4fcb96222c064e8a0f22fdd2f6,frontend/src/utils/ExpressHttpHandler.js,作者留存]. 2026 年 11 月 17 日核对该历史文件;提交纳入代码的日期与 5 月 12 日已经讨论和调试的日期分别记录,不公开业务仓库或认证数据。 ↩ ↩2 ↩3 ↩4 ↩5

  15. Cai, B. [S2thend]. (2024, March 27). Myxios response interceptor dispatch [提交 bc40f97]. GitHub. 以 reduce 组织处理函数并保留各层结果。对两个库接口风格和预期读者的回忆补记于 2026-11-24。 ↩

  16. Cai, B. [S2thend]. (2025, May 13). Express Http Client [README,提交 7357757,简介第 2 段及体积徽章]. GitHub. https://github.com/S2thend/express-http-client/blob/7357757b17eb6cdefdba04a6fc4b9fe8cc3be514/README.md 。引用保留原文语法;体积为 README 当时标注值,并非本次实测。 ↩ ↩2 ↩3

  17. Angular team. (n.d.). interceptor.ts [v17.3.12,chainedInterceptorFn、adaptLegacyInterceptorToChain 和 HttpInterceptorHandler.handle]. GitHub. 函数式与类式拦截器的委托和组链源码。 这个组链办法可追溯到 Angular 4.3.0(2017 年 7 月):当时已用 reduceRight 从后端向外包装处理器,类式接口通过 next.handle(req) 放行。直接调用 next(req) 的函数式接口由 PR #47502 引入,随 Angular 15.0.0 于 2022 年 11 月 16 日发布。 ↩ ↩2

  18. CaiBorui. (2025, May 6–12). Adding Request and Response Interceptors [未公开开发对话,作者留存]. Cursor. 引文出自消息 15;消息 25 讨论异步回调何时放行。文章按建仓日期归档。 ↩ ↩2 ↩3

  19. MDN contributors. (n.d.). Private elements. MDN Web Docs. Simulating private constructors,静态标记和工厂方法示例。Firefox 记录于 2025-05-11 18:09 打开当时名为 Private properties 的页面,18:10 进入该小节。 ↩

  20. Cai, B. [S2thend]. (2025, May 12). First functional prototype version [提交 40899b4,index.js 与 README]. GitHub. https://github.com/S2thend/express-http-client/commit/40899b496cad46b59f238fa0ad72f78f11691e0b 。原型 README 包含认证头、401 刷新 token 与重发请求的示例;共享状态机制的使用示例另见 Fetch 与 Request 技术篇。 ↩ ↩2

  21. CaiBorui. (2025, May 12). Updating Request Object in JavaScript [未公开开发对话,消息 5、7、9,作者留存]. Cursor. ↩

  22. MDN contributors. (n.d.). Iteration protocols [The iterator protocol]. MDN Web Docs. 迭代器的 next 方法与返回值。 ↩

  23. Express contributors. (n.d.). Express. GitHub. 源码入口有 express.js、request.js 和 application.js。对照 v5.1.0 可见 express.js 创建应用和请求原型、request.js 从 Node 的 IncomingMessage 继承、application.js 引入 router 包、初始化应用路由器及把请求和响应交给路由器。 ↩

  24. PillarJS contributors. (n.d.). index.js. GitHub. 原分支链接为 L291 和 L576。v2.2.0 中对应的两处实现是处理路径参数后调用路由处理函数、processParams 按顺序取参数及其回调。 ↩

  25. Cai, B. [S2thend]. (2025, May 13). Add simple mock response interceptor middleware [提交 aff2a62]. GitHub. https://github.com/S2thend/express-http-client/commit/aff2a62c2c88ac6e1b88ef47024d2270ecee9121 。日志读取 method 与 url 的代码见同日快照 Logger.js。 ↩ ↩2 ↩3

  26. Eclipse Foundation. (n.d.). FilterChain [Jakarta Servlet 6.0,doFilter 方法]. Jakarta EE. 传给下一层过滤器的调用约定。 ↩

  27. Axios contributors. (n.d.). URL-Encoding Bodies and Multipart Bodies. Axios. URL 编码表单、multipart 表单。2025 年 5 月 11 日的访问记录还包括旧版示例页 axios-http.com/docs/example。对应的现行文档见 JavaScript examples(Post request)、x-www-form-urlencoded format 和 multipart-form-data format。 ↩

  28. CaiBorui. (2026, November 25). Express Http Client 0.3.6 表单提交验证 [本地实测]. Node.js 22.12.0,使用 CommonJS 构建和本机 HTTP 服务。两个入口各做三次首次 POST,服务端解析 JSON 或表单,并核对字段、重复值与文件内容。multipart 使用带文件名的 Blob。测试范围不含浏览器、上传进度和 401 后的文件重发。源码见 HttpClient.send 和 request。 ↩

  29. MDN contributors. (n.d.). Using FormData objects. MDN Web Docs. Sending files using a FormData object,文件字段与 multipart 边界。 ↩

  30. Express contributors. (n.d.). Error handling. Express. Retrieved May 12, 2025, from Error handling,四参数签名与返回错误响应的示例见 Writing error handlers。 ↩

  31. Cai, B. [S2thend]. (2025, May 13). Add try catch for fetch request to ensure adherent behavior [提交 8784705]. GitHub. 将 Fetch 异常转为响应再执行响应链。 ↩ ↩2

  32. Axios contributors. (n.d.). Axios.js [v1.7.0,组装请求与响应拦截器链]. GitHub. 请求链用 unshift,响应链用 push。 ↩

  33. Cai, B. [S2thend]. (2025, May 13). express-http-client package.json [版本 0.3.6,提交 1095d94]. GitHub. https://github.com/S2thend/express-http-client/blob/1095d94faf40a3b9c7132af5d1076260e124a8e0/package.json 。仅列开发依赖,无运行时依赖。 ↩

  34. OpenAI. (2025, March 27). OpenAI Node API library [v4.90.0]. GitHub. ClientOptions.fetch 的注释及 Node.js 默认实现,第 170–176 行。 ↩ ↩2

  35. Vercel. (n.d.). OpenAI(Provider Instance,fetch 选项). AI SDK. 接入包的实例设置。2026 年 12 月 2 日核对。 ↩

  36. Axios contributors. (n.d.). Fetch adapter [v1.7.0]. GitHub. 读取响应并构造 Axios 响应对象。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-06). Designing a Fetch client with Express-style middleware. https://caiborui.com/blog/2025-05-06-zh-express-http-client-design-entrans

@misc{borui2025-14406a28,
  author = {borui},
  title = {{Designing a Fetch client with Express-style middleware}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-06-zh-express-http-client-design-entrans}
}