diff --git a/src/service/wp.service.ts b/src/service/wp.service.ts index 7cba5a4..1cb3a75 100644 --- a/src/service/wp.service.ts +++ b/src/service/wp.service.ts @@ -11,6 +11,24 @@ export class WPService { @Config('wpSite') sites: WpSite[]; + /** + * 构建 URL,自动规范各段的斜杠,避免出现多 / 或少 / 导致请求失败 + * 使用示例:this.buildURL(wpApiUrl, '/wp-json', 'wc/v3/products', productId) + */ + private buildURL(base: string, ...parts: Array): string { + // 去掉 base 末尾多余斜杠,但不影响协议中的 // + const baseSanitized = String(base).replace(/\/+$/g, ''); + // 规范各段前后斜杠 + const segments = parts + .filter((p) => p !== undefined && p !== null) + .map((p) => String(p)) + .map((s) => s.replace(/^\/+|\/+$/g, '')) + .filter(Boolean); + const joined = [baseSanitized, ...segments].join('/'); + // 折叠除协议外的多余斜杠,例如 https://example.com//a///b -> https://example.com/a/b + return joined.replace(/([^:])\/{2,}/g, '$1/'); + } + /** * 获取 WordPress 数据 * @param wpApiUrl WordPress REST API 的基础地址 @@ -31,7 +49,8 @@ export class WPService { ): Promise { try { const { wpApiUrl, consumerKey, consumerSecret } = site; - const url = `${wpApiUrl}/wp-json${endpoint}`; + // 构建 URL,规避多/或少/问题 + const url = this.buildURL(wpApiUrl, '/wp-json', endpoint); const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString( 'base64' ); @@ -64,7 +83,8 @@ export class WPService { while (hasMore) { const config: AxiosRequestConfig = { method: 'GET', - url: `${wpApiUrl}/wp-json${endpoint}`, + // 构建 URL,规避多/或少/问题 + url: this.buildURL(wpApiUrl, '/wp-json', endpoint), headers: { Authorization: `Basic ${auth}`, }, @@ -212,7 +232,8 @@ export class WPService { ); const config: AxiosRequestConfig = { method: 'PUT', - url: `${wpApiUrl}/wp-json${endpoint}`, + // 构建 URL,规避多/或少/问题 + url: this.buildURL(wpApiUrl, '/wp-json', endpoint), headers: { Authorization: `Basic ${auth}`, }, @@ -310,7 +331,14 @@ export class WPService { ); const config: AxiosRequestConfig = { method: 'POST', - url: `${wpApiUrl}/wp-json/wc-ast/v3/orders/${orderId}/shipment-trackings`, + // 构建 URL,规避多/或少/问题 + url: this.buildURL( + wpApiUrl, + '/wp-json', + 'wc-ast/v3/orders', + orderId, + 'shipment-trackings' + ), headers: { Authorization: `Basic ${auth}`, }, @@ -333,7 +361,15 @@ export class WPService { // 删除接口: DELETE /wp-json/wc-shipment-tracking/v3/orders//shipment-trackings/ const config: AxiosRequestConfig = { method: 'DELETE', - url: `${wpApiUrl}/wp-json/wc-ast/v3/orders/${orderId}/shipment-trackings/${trackingId}`, + // 构建 URL,规避多/或少/问题 + url: this.buildURL( + wpApiUrl, + '/wp-json', + 'wc-ast/v3/orders', + orderId, + 'shipment-trackings', + trackingId + ), headers: { Authorization: `Basic ${auth}`, },