Skip to content
Open
Changes from 2 commits
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
52 changes: 52 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,60 @@
'use strict';

const http = require('http');
const fs = require('fs');

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer(async (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 server listens for POST requests to /add-expense, but the form submits to /submit-expense. This will cause the form submission to fail.

try {
let body = '';

req.on('data', (chunk) => {
body += chunk.toString();
});

req.on('end', () => {
const expense = JSON.parse(body);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Issue: The code attempts to parse the request body as JSON, but the HTML form submits data as URL-encoded form data, not JSON. This will cause a parsing error. You need to parse the body as URL-encoded data or change the form to submit JSON (which is not typical for HTML forms).


const { date, title, amount } = expense;

if (!date || !title || !amount) {
res.writeHead(400);

return res.end('Missing required fields');
}

fs.writeFileSync('db/expense.json', JSON.stringify(expense));

const file = fs.readFileSync('db/expense.json');

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

Choose a reason for hiding this comment

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

Issue: The response to the POST request is sent as raw JSON with 'application/json' content type. According to the task, you should return an HTML page with the JSON data formatted within it, not just the JSON string.

});
} catch (err) {
res.writeHead(500);
res.end('Error parsing form');
}
} else if (req.method === 'GET' && req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html');

res.end(`<h1>Input data</h1>
<form method="POST" action="/add-expense">
<input name="date" type="date" required>
<input name="title" type="text" required>
<input name="amount" type="number" required>

<button type="submit">Submit</button>
</form>`);
} else {
res.statusCode = 404;
res.end('Page not found');
}
});
}

module.exports = {
Expand Down