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

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
if (
req.method === 'GET' &&
(req.url === '/' || req.url === '/index.html')
) {
res.setHeader('Content-Type', 'text/html');
res.statusCode = 200;

res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Expense Form</title>
</head>
<body>
<form action="/add-expense" method="POST">
<input type="date" name="date" required>
<input type="text" name="title" required>
<input type="number" name="amount" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
`);

return;
}

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

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

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

try {
// It could be JSON (for tests) or url-encoded (for standard forms)
if (req.headers['content-type'] === 'application/json') {
expense = JSON.parse(body);
} else {
expense = Object.fromEntries(new URLSearchParams(body));
}
} catch (e) {
res.statusCode = 400;
res.end('Invalid request formats');

return;
}

const { date, title, amount } = expense;

if (!date || !title || !amount) {
res.statusCode = 400;
res.end('Missing required fields');

return;
}

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

fs.writeFile(dataPath, JSON.stringify(expense, null, 2), (err) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');

return;
}

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
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 task specifies that the app should 'return an HTML page with well formatted JSON' after receiving and saving the data. Currently, the server sets the Content-Type to application/json and sends the JSON directly. Please modify this to embed the JSON within an HTML structure, ensuring the Content-Type is set to text/html.

res.end(JSON.stringify(expense));
});
});

return;
}

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

module.exports = {
Expand Down