// 引入 Node.js 的 http 模块 const http = require('http'); // 创建一个 HTTP 服务器 const server = http.createServer((req, res) => { // 设置跨域头 res.setHeader('Access-Control-Allow-Origin', '*'); // 允许所有来源访问(不建议在生产环境中使用 ' * ') res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // 允许的 HTTP 方法 res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 允许的请求头 // 处理预检请求(OPTIONS) if (req.method === 'OPTIONS') { res.statusCode = 204; res.end(); return; } // 设置响应头 res.setHeader('Content-Type', 'text/plain'); // 检查请求方法是否为 GET,并检查请求的路径 if (req.method === 'GET' && req.url === '/test') { // 返回 "hello world" res.end('hello world'); } else { // 如果不是 GET 请求,返回 405 Method Not Allowed // 如果请求的路径不是 /test,返回 404 Not Found if (req.method === 'GET') { res.statusCode = 404; res.end('Not Found'); } else { res.statusCode = 405; res.end('Method Not Allowed'); } } }); // 监听端口 1234 const PORT = 1234; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });