Skip to content
Open

task #182

Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,51 @@
'use strict';

const http = require('node:http');
const fs = require('node:fs');
const path = require('path');

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.createServer((req, res) => {
if (req.method !== 'POST' || req.url !== '/add-expense') {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The requirements state that the application should show an HTML form. This server logic only accepts POST requests to /add-expense and returns a 404 Not Found for all other requests, including GET requests that would typically be used to serve the form.

res.statusCode = 404;
res.end('Not Found');

return;
}

const chunks = [];

req.on('data', (chunk) => {
chunks.push(chunk);
});

req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf-8');

const expense = JSON.parse(body);

if (!expense.date || !expense.title || !expense.amount) {
res.statusCode = 400;
res.setHeader('Content-Type', 'text/plain');
res.end('Missing required fields');

return;
}

const dataPath = path.resolve(__dirname, '../db/expense.json');

fs.writeFile(dataPath, body, (error) => {
if (error) {
}
});

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(expense));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block has several issues related to asynchronous operations and task requirements:

  1. Race Condition: fs.writeFile is asynchronous. The response is sent on lines 42-44 without waiting for the file to be written. All response logic, for both success and error, should be moved inside this callback.
  2. Missing Error Handling: The error object is not handled on line 38. If writing to the file fails, the server will still send a 200 OK response. You should handle this case and send an appropriate error response (e.g., status 500).
  3. Incorrect Response Format: The task requires returning an "HTML page with well formatted JSON". This code sends a raw JSON response with Content-Type: application/json. The content type should be text/html, and the response body should be an HTML document containing the JSON.

});
});

return server;
}

module.exports = {
Expand Down