test-server-500.js 2.46 KB
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错误');
});