Add utility functions for handling public URLs and update API base URL logic
- Implement getProductionApiBaseUrl and normalizePublicUrl functions to manage API URLs based on the browser's origin. - Update API base URL in request configuration to use getProductionApiBaseUrl. - Enhance QR code handling in ParticipatingCompaniesTab and OutdoorFairList components to normalize URLs. - Create a deployment script for frontend builds and server uploads. - Add tests for the new URL utility functions.
This commit is contained in:
37
src/utils/publicUrl.ts
Normal file
37
src/utils/publicUrl.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const INTERNAL_HOSTS = new Set(['127.0.0.1', 'localhost', '0.0.0.0', '::1']);
|
||||
|
||||
function getBrowserOrigin() {
|
||||
return typeof window === 'undefined' ? '' : window.location.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生产环境 API 使用当前浏览器访问的 origin,避免把后端内网地址编译进前端产物。
|
||||
*/
|
||||
export function getProductionApiBaseUrl(origin = getBrowserOrigin()) {
|
||||
const normalizedOrigin = origin.replace(/\/+$/, '');
|
||||
return `${normalizedOrigin || ''}/api/shihezi/`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后端可能因为反向代理配置返回内网 H5 地址,前端展示和打开二维码时使用当前公开 origin。
|
||||
*/
|
||||
export function normalizePublicUrl(value?: string, currentOrigin = getBrowserOrigin()) {
|
||||
if (!value || !currentOrigin || !/^https?:\/\//i.test(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(value);
|
||||
const browserUrl = new URL(currentOrigin);
|
||||
if (
|
||||
INTERNAL_HOSTS.has(url.hostname.toLowerCase()) &&
|
||||
!INTERNAL_HOSTS.has(browserUrl.hostname.toLowerCase())
|
||||
) {
|
||||
url.protocol = browserUrl.protocol;
|
||||
url.host = browserUrl.host;
|
||||
}
|
||||
return url.toString();
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user