template-demo/utils/httpClient.js

89 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 统一的 HTTP 客户端
* 自动根据环境切换使用 gatewayHttpClient 或 HttpClient
*/
import { gatewayHttpClient, HttpClient } from '@jdmini/api'
const { IS_DEV, API_BASE } = require('./config.js')
// 开发环境使用 HttpClient
const devHttpClient = IS_DEV ? new HttpClient({
baseURL: API_BASE,
timeout: 30000,
}) : null
/**
* 统一的 HTTP 请求方法
* @param {String} url - 请求路径(相对路径,不包含 baseURL
* @param {String} method - 请求方法 GET/POST/PUT/DELETE
* @param {Object} data - 请求数据
* @param {Object} options - 额外选项
* @returns {Promise}
*/
function request(url, method = 'GET', data = {}, options = {}) {
// 确保 URL 以 / 开头
const apiUrl = url.startsWith('/') ? url : `/${url}`
if (IS_DEV) {
// 开发环境:使用 HttpClient
console.log(`[DEV] ${method} ${API_BASE}${apiUrl}`, data)
return devHttpClient.request(apiUrl, method, data, options)
} else {
// 生产环境:使用 gatewayHttpClient
// gatewayHttpClient 需要完整的路径mp/jd-haiba/user/login
const fullUrl = `${API_BASE}${apiUrl}`
console.log(`[PROD] ${method} ${fullUrl}`, data)
// gatewayHttpClient.request 的参数顺序:(url, method, data, options)
return gatewayHttpClient.request(fullUrl, method, data, options)
}
}
/**
* GET 请求
*/
function get(url, params = {}, options = {}) {
return request(url, 'GET', params, options)
}
/**
* POST 请求
*/
function post(url, data = {}, options = {}) {
return request(url, 'POST', data, options)
}
/**
* PUT 请求
*/
function put(url, data = {}, options = {}) {
return request(url, 'PUT', data, options)
}
/**
* DELETE 请求
*/
function del(url, data = {}, options = {}) {
return request(url, 'DELETE', data, options)
}
/**
* 上传文件(暂时保留原有逻辑)
*/
function upload(filePath, formData = {}) {
return gatewayHttpClient.uploadFile(filePath,formData)
}
module.exports = {
request,
get,
post,
put,
del,
upload,
// 导出原始客户端供特殊场景使用
gatewayHttpClient,
devHttpClient
}