diff --git a/package.json b/package.json index 75a299a..a925a85 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kevisual/query", - "version": "0.0.48", + "version": "0.0.49", "type": "module", "scripts": { "build": "npm run clean && bun run bun.config.ts", diff --git a/src/query.ts b/src/query.ts index df0fc6e..9a45178 100644 --- a/src/query.ts +++ b/src/query.ts @@ -20,13 +20,14 @@ export type QueryOpts = { export type QueryOptions = { url?: string; + baseURL?: string; + beforeRequest?: Fn; adapter?: typeof adapter; headers?: Record; timeout?: number; isClient?: boolean; tokenName?: string; storage?: Storage; - beforeRequest?: Fn; } export type Data = { path?: string; @@ -67,6 +68,7 @@ export const wrapperError = ({ code, message }: { code?: number; message?: strin */ export class Query { adapter: typeof adapter; + baseURL: string; url: string; /** * 请求前处理函数 @@ -93,6 +95,11 @@ export class Query { this.storage = opts?.storage || globalThis?.localStorage; const defaultURL = opts?.isClient ? '/client/router' : '/api/router'; this.url = opts?.url || defaultURL; + if (this.url.startsWith('http')) { + const urlObj = new URL(this.url); + this.baseURL = urlObj.origin; + } + this.baseURL = opts?.baseURL || this.baseURL; // 如果opts中有baseURL优先 this.headers = opts?.headers || { 'Content-Type': 'application/json', }; @@ -155,6 +162,14 @@ export class Query { timeout: _timeout, ...rest, }; + const isStartsWithHttp = req.url.startsWith('http'); + // 如果是完整的url,直接使用, 如果不是完整的url,且baseURL存在,则拼接baseURL + if (!isStartsWithHttp) { + if (this.baseURL) { + const baseURL = new URL(this.baseURL || globalThis?.location?.origin).origin; + req.url = baseURL + req.url; + } + } try { if (_beforeRequest) { const res = await _beforeRequest(req);