Skip to the content.

Shared Middleware

通过 Fetcher 构造函数注入公共中间件的示例。

import { Fetcher, POST, json } from 'es-fetch-api'
import { getToken } from './auth'

const useToken = async (ctx, next) => {
    ctx.header('Authorization', `Bearer ${await getToken()}`)
    return next()
}

const useTimestamp = (ctx, next) => {
    ctx.header('X-Timestamp', String(Date.now()))
    return next()
}

const { getJSON, exec } = new Fetcher(
    'https://example.com/api/v1',
    useToken,
    useTimestamp
)

export const createUser = payload => getJSON('users', POST, json(payload))
export const getUser = id => exec(`users/${id}`)

适用场景: