Files
ip-service/ip-service.js
Coding Expert 8e25bf51b8 feat: 初始版本 - 跨平台 IP 地址查询服务
- 后端服务 (Express + ES5)
  - 支持获取真实客户端 IP
  - 支持代理服务器 (X-Forwarded-For)
  - IP 地理位置查询
  - 内存缓存优化 (10 分钟 TTL)
  - 健康检查接口

- 前端客户端 (ES5 兼容)
  - IPService 类库
  - 支持回调函数
  - 示例页面

- 跨平台部署
  - Windows 启动脚本 (start.bat)
  - Linux 启动脚本 (start.sh)
  - PM2 生产环境支持

- 文档
  - README.md 完整说明
  - .gitignore 配置
2026-03-23 09:39:32 +08:00

87 lines
1.9 KiB
JavaScript

/**
* IP 服务客户端 (ES5 兼容)
* @version 1.0.0
*/
var IPService = (function() {
'use strict';
function IPService(baseURL) {
this.baseURL = baseURL || '';
}
/**
* 获取 IP 地址
* @param {Function} callback - 回调函数 callback(error, data)
*/
IPService.prototype.getIP = function(callback) {
var self = this;
this._request(this.baseURL + '/api/get-ip', function(err, data) {
if (callback) {
callback(err, data);
}
});
};
/**
* 获取 IP + 地理位置信息
* @param {Function} callback - 回调函数 callback(error, data)
*/
IPService.prototype.getIPInfo = function(callback) {
var self = this;
this._request(this.baseURL + '/api/get-ip-info', function(err, data) {
if (callback) {
callback(err, data);
}
});
};
/**
* 内部请求方法
* @private
*/
IPService.prototype._request = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
var data = JSON.parse(xhr.responseText);
callback(null, data);
} catch (e) {
callback(new Error('JSON parse failed'), null);
}
} else {
callback(new Error('HTTP ' + xhr.status), null);
}
};
xhr.onerror = function() {
callback(new Error('Network error'), null);
};
xhr.ontimeout = function() {
callback(new Error('Request timeout'), null);
};
xhr.timeout = 10000; // 10 秒超时
xhr.send();
};
return IPService;
})();
// 导出到全局作用域
if (typeof window !== 'undefined') {
window.IPService = IPService;
}
// 导出为 CommonJS 模块
if (typeof module !== 'undefined' && module.exports) {
module.exports = IPService;
}