test-server-500.js
2.46 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// 设置CORS头
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// 处理OPTIONS预检请求
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
console.log(`${new Date().toISOString()} - ${req.method} ${path}`);
// 路由处理
if (path === '/api/test-500') {
// 返回500服务器错误
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
code: 500,
message: '服务器内部错误',
error: 'Internal Server Error',
timestamp: new Date().toISOString()
}));
} else if (path === '/api/test-success') {
// 返回成功响应
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
code: 0,
message: '请求成功',
data: {
timestamp: new Date().toISOString(),
status: 'success'
}
}));
} else if (path === '/api/test-error') {
// 返回业务错误(HTTP 200但业务code非0)
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
code: 40001,
message: '业务逻辑错误',
data: null
}));
} else if (path === '/api/test-logout') {
// 返回需要登出的响应
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
code: 40003,
message: '用户未登录或登录已过期',
data: null
}));
} else {
// 404错误
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
code: 404,
message: '接口不存在',
error: 'Not Found',
path: path
}));
}
});
const PORT = 3002;
server.listen(PORT, () => {
console.log(`测试服务器运行在 http://localhost:${PORT}`);
console.log('可用的测试端点:');
console.log(' GET /api/test-500 - 返回500服务器错误');
console.log(' GET /api/test-success - 返回成功响应');
console.log(' GET /api/test-error - 返回业务错误(HTTP 200)');
console.log(' GET /api/test-logout - 返回登出响应');
console.log(' GET /api/not-found - 返回404错误');
});