-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathproxy-server.js
More file actions
62 lines (54 loc) · 1.83 KB
/
proxy-server.js
File metadata and controls
62 lines (54 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const morgan = require('morgan');
const app = express();
// 启用详细日志记录
app.use(morgan('dev'));
// 启用CORS
app.use(cors());
// 静态文件服务
app.use(express.static(path.join(__dirname)));
// 代理API请求
app.use('/api/coze', createProxyMiddleware({
target: 'https://api.coze.cn',
changeOrigin: true,
pathRewrite: {
'^/api/coze': '/v3/chat'
},
onProxyReq: (proxyReq, req, res) => {
// 添加必要的请求头
const apiKey = process.env.COZE_API_KEY || 'pat_vnJOJjNCzgkFCfuBxTiqeA69DWJSxNgnOrPZWKca6IfRca5LuJDYihHtfV359lqV';
proxyReq.setHeader('Authorization', `Bearer ${apiKey}`);
console.log(`代理请求到Coze API: ${req.method} ${req.url}`);
},
onProxyRes: (proxyRes, req, res) => {
console.log(`收到来自Coze API的响应: ${proxyRes.statusCode}`);
},
onError: (err, req, res) => {
console.error('代理请求错误:', err);
res.status(500).send({
error: '代理请求失败',
message: err.message
});
}
}));
// 错误处理中间件
app.use((err, req, res, next) => {
console.error('服务器错误:', err);
res.status(500).send({
error: '服务器错误',
message: err.message
});
});
// 所有其他请求返回index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`代理服务器运行在 http://localhost:${PORT}`);
console.log('API密钥:', process.env.COZE_API_KEY ? '已设置环境变量' : '使用默认值');
console.log('按 Ctrl+C 停止服务器');
});