Skip to the content.

URL Behavior

本文件说明 URL 相关行为,包括 baseUrl 支持和 endpoint 拼接规则。

Base URL 行为

new Fetcher(baseUrl)baseUrl 参数支持:

示例:

import { Fetcher } from 'es-fetch-api'

const fixedFetcher = new Fetcher('https://example.com/api/v1')

const dynamicFetcher = new Fetcher(async () => {
    const config = await fetchConfig()
    return config.apiBaseUrl
})

const rawFetcher = new Fetcher()
rawFetcher.exec('https://example.com/api/v1/users') // ✓ 可行
rawFetcher.exec('users') // ✗ 报错:Invalid URL

Endpoint 拼接规则

写 endpoint 时注意:

示例:

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

exec('users')                  // => https://example.com/api/v1/users
exec('/users/')                // => https://example.com/api/v1/users
exec('https://other.com/ping') // => https://other.com/ping