Skip to content
Open
Show file tree
Hide file tree
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
27 changes: 27 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Data</title>
</head>

<body>
<h1>Form Data</h1>
<form action="/add-expense" method="post" enctype="application/x-www-form-urlencoded">
<label for="date">Date:</label>
<input id="date" name="date" type="date"/>
<br />
<br />
<label for="title">Title:</label>
<input id="title" name="title" type="text"/>
<br />
<br />
<label for="amount">Amount:</label>
<input id="amount" name="amount" type="number"/>
<br />
<br />
<button type="submit">Send</button>
</form>
</body>
</html>
85 changes: 83 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,89 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
const server = http.createServer((req, res) => {
const reqUrl = new URL(req.url || '', `http://${req.headers.host}`);
const pathname = reqUrl.pathname;

if (req.method === 'GET' && pathname === '/') {
const indexPath = path.resolve('public', 'index.html');

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream(indexPath).pipe(res);

return;
}

if (req.method === 'GET' && pathname === '/add-expense') {
res.statusCode = 400;

return res.end('Only POST method allowed');
}

if (req.method === 'POST' && pathname === '/add-expense') {
let body = '';

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

req.on('end', () => {
let dataObj;

try {
const contentType = req.headers['content-type'];

if (contentType.includes('application/json')) {
dataObj = JSON.parse(body);
} else if (
contentType.includes('application/x-www-form-urlencoded')
) {
const parsed = new URLSearchParams(body);

dataObj = Object.fromEntries(parsed.entries());
} else {
res.writeHead(400, { 'Content-Type': 'text/plain' });

return res.end('Unsupported content type');
}

const { date, title, amount } = dataObj;

if (!date || !title || !amount) {
res.writeHead(400, { 'Content-Type': 'text/plain' });

return res.end('Invalid data format');
}

const dataJSON = JSON.stringify(dataObj, null, 2);
const filePath = path.resolve('db', 'expense.json');

fs.writeFile(filePath, dataJSON, (err) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });

return res.end(`Server error: ${err}`);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(dataJSON);
});
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 overwrites 'db/expense.json' with each new POST request instead of appending new expenses. If the task requires storing multiple expenses, you should read the existing file, parse it as an array, push the new expense, and then write the updated array back to the file. Please check the task description or checklist to confirm the required behavior.

} catch (e) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end(`Invalid request body: ${e.message}`);
}
});
} else {
res.statusCode = 404;
res.end('Not found');
}
});

return server;
}

module.exports = {
Expand Down