main.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // 引入 Node.js 的 http 模块
  2. const http = require('http');
  3. // 创建一个 HTTP 服务器
  4. const server = http.createServer((req, res) => {
  5. // 设置跨域头
  6. res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有来源访问(不建议在生产环境中使用 ' * ')
  7. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // 允许的 HTTP 方法
  8. res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 允许的请求头
  9. // 处理预检请求(OPTIONS)
  10. if (req.method === 'OPTIONS') {
  11. res.statusCode = 204;
  12. res.end();
  13. return;
  14. }
  15. // 设置响应头
  16. res.setHeader('Content-Type', 'text/plain');
  17. // 检查请求方法是否为 GET,并检查请求的路径
  18. if (req.method === 'GET' && req.url === '/test') {
  19. // 返回 "hello world"
  20. res.end('hello world');
  21. } else {
  22. // 如果不是 GET 请求,返回 405 Method Not Allowed
  23. // 如果请求的路径不是 /test,返回 404 Not Found
  24. if (req.method === 'GET') {
  25. res.statusCode = 404;
  26. res.end('Not Found');
  27. } else {
  28. res.statusCode = 405;
  29. res.end('Method Not Allowed');
  30. }
  31. }
  32. });
  33. // 监听端口 1234
  34. const PORT = 1234;
  35. server.listen(PORT, () => {
  36. console.log(`Server is running on http://localhost:${PORT}`);
  37. });