(method, basePath)
| 231 | } |
| 232 | |
| 233 | proxyRequest(method, basePath) { |
| 234 | return async (req, res) => { |
| 235 | try { |
| 236 | const fetch = (await import('node-fetch')).default; |
| 237 | |
| 238 | // 构建完整URL |
| 239 | let url = `${this.apiBaseUrl}${basePath}`; |
| 240 | if (req.params) { |
| 241 | // 替换路径参数 |
| 242 | Object.entries(req.params).forEach(([key, value]) => { |
| 243 | url = url.replace(`:${key}`, value); |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | // 添加查询参数 |
| 248 | if (req.query && Object.keys(req.query).length > 0) { |
| 249 | const searchParams = new URLSearchParams(req.query); |
| 250 | url += `?${searchParams.toString()}`; |
| 251 | } |
| 252 | |
| 253 | // 准备请求选项 |
| 254 | const options = { |
| 255 | method, |
| 256 | headers: { |
| 257 | 'Content-Type': 'application/json', |
| 258 | ...req.headers |
| 259 | } |
| 260 | }; |
| 261 | |
| 262 | // 添加请求体(对于POST、PUT等) |
| 263 | if (['POST', 'PUT', 'PATCH'].includes(method) && req.body) { |
| 264 | options.body = JSON.stringify(req.body); |
| 265 | } |
| 266 | |
| 267 | // 发送请求到后端 |
| 268 | const response = await fetch(url, options); |
| 269 | const data = await response.json(); |
| 270 | |
| 271 | // 转发响应 |
| 272 | res.status(response.status).json(data); |
| 273 | |
| 274 | } catch (error) { |
| 275 | console.error('API代理错误:', error); |
| 276 | res.status(500).json({ |
| 277 | error: 'API请求失败', |
| 278 | message: error.message |
| 279 | }); |
| 280 | } |
| 281 | }; |
| 282 | } |
| 283 | |
| 284 | |
| 285 |
no test coverage detected