* Handles API requests to /api. * * Collects request data, parses it as JSON, and returns a JSON response * containing the request URL, method, headers, and parsed data. * * @param {http.IncomingMessage} req - The HTTP request object. * @param {http.ServerResponse} res - The HTTP response obje
(req, res)
| 31 | * @param {http.ServerResponse} res - The HTTP response object. |
| 32 | */ |
| 33 | function handleApiRequest(req, res) { |
| 34 | let status; |
| 35 | let result; |
| 36 | let data = ''; |
| 37 | |
| 38 | req.on('data', (chunk) => { |
| 39 | data += chunk; |
| 40 | }); |
| 41 | |
| 42 | req.on('end', () => { |
| 43 | try { |
| 44 | status = 200; |
| 45 | result = { |
| 46 | url: req.url, |
| 47 | data: data ? JSON.parse(data) : undefined, |
| 48 | method: req.method, |
| 49 | headers: req.headers, |
| 50 | }; |
| 51 | } catch (e) { |
| 52 | console.error('Error:', e.message); |
| 53 | status = 400; |
| 54 | result = { |
| 55 | error: e.message, |
| 56 | }; |
| 57 | } |
| 58 | |
| 59 | res.writeHead(status, { |
| 60 | 'Content-Type': 'application/json', |
| 61 | }); |
| 62 | res.end(JSON.stringify(result)); |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Handles incoming HTTP requests. |