服务通讯
服务通讯
本文档详细介绍了 GM Web SDK 支持的各种通讯方式,帮助您的应用与 GM 后台服务和系统进行高效交互。
概述
GM 提供了多种通讯能力,包括与后台服务的 HTTP 通讯、代理转发和系统命令执行等功能。
前置条件
重要提示
在使用任何通讯功能之前,必须先调用 $gm.init()
方法并等待其成功回调,确保 SDK 完全初始化后再进行通信操作。
// 正确的初始化流程
$gm.init().then(() => {
console.log('SDK 初始化成功,可以开始通信');
// 在这里进行通信操作
}).catch(error => {
console.error('SDK 初始化失败:', error);
});
详细信息请参考 初始化 API 文档。
HTTP 通讯
request
request
是基于 Axios 封装的 HTTP 客户端实例,专门用于与 GM 后台服务进行通信。
类型定义:
属性名 | 类型 | 说明 |
---|---|---|
request | AxiosInstance | Axios 实例,支持所有 Axios 配置选项 |
使用示例:
// GET 请求
$gm.request.get('/api/user/profile')
.then(response => {
console.log('用户信息:', response.data);
})
.catch(error => {
console.error('请求失败:', error);
});
// POST 请求
$gm.request.post('/api/files/get_dir', {
path: '/',
search: '',
all: false,
showRow: 9999
}).then(response => {
console.log('目录信息:', response.data);
}).catch(error => {
console.error('获取目录失败:', error);
});
// 使用配置对象
$gm.request({
url: '/api/data',
method: 'PUT',
data: { id: 1, name: 'updated' },
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log('更新成功:', response.data);
}).catch(error => {
console.error('更新失败:', error);
});
apiForward
apiForward
提供代理转发功能,允许您通过 GM 代理访问外部 API 服务,解决跨域问题并统一管理外部请求。
参数说明:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
url | string | ✅ | 目标 API 地址 |
options.method | string | ✅ | HTTP 请求方法 |
options.headers | object | ❌ | 请求头信息 |
options.body | any | ❌ | 请求体数据 |
options.timeout | number | ❌ | 超时时间(毫秒),默认 30000 |
使用示例:
// 基础 GET 请求
$gm.apiForward('https://api.example.com/users', {
method: 'GET'
}).then(response => {
console.log('用户列表:', response);
}).catch(error => {
console.error('请求失败:', error);
});
// POST 请求with JSON 数据
$gm.apiForward('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: {
name: '张三',
email: 'zhangsan@example.com'
},
timeout: 10000
}).then(response => {
console.log('创建成功:', response);
}).catch(error => {
console.error('创建失败:', error);
});
系统命令执行
execShell
execShell
允许您在前端直接执行系统 Shell 命令,适用于需要与系统进行深度交互的场景。
安全提示
执行 Shell 命令具有潜在的安全风险,请确保命令来源可信,避免执行用户输入的未验证命令。
参数说明:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
cmd | string | ✅ | 要执行的 Shell 命令 |
timeout | number | ❌ | 超时时间(秒) |
cwd | string | ❌ | 命令执行目录,默认当前工作目录 |
name | string | ❌ | 执行用户名(仅限特定环境) |
使用示例:
// 基础命令执行
$gm.execShell({
cmd: 'ls -la'
}).then(result => {
console.log('命令输出:', result.stdout);
console.log('退出码:', result.exitCode);
if (result.stderr) {
console.warn('错误输出:', result.stderr);
}
}).catch(error => {
console.error('命令执行失败:', error);
});
// 在指定目录执行命令
$gm.execShell({
cmd: 'npm install',
cwd: '/path/to/project',
timeout: 60000 // 1分钟超时
}).then(result => {
if (result.exitCode === 0) {
console.log('npm install 成功完成');
} else {
console.error('npm install 失败:', result.stderr);
}
}).catch(error => {
console.error('命令执行失败:', error);
});