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
53 changes: 53 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,61 @@
'use strict';

const http = require('http');
const { IncomingForm } = require('formidable');
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.

const form = new IncomingForm({ multiples: false });

try {
const [fields] = await form.parse(req);

const { date, title, amount } = fields;

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

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

const result = JSON.stringify(fields);

// console.log('Fields:', fields);

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

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(result);
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 description asks to return an HTML page with well-formatted JSON, but the code returns a JSON string directly. You should wrap the JSON in an HTML page.


// res.end(`<div>
// <h1>Date: ${fields['date']}</h1>
// <h1>Title: ${fields['title']}</h1>
// <h1>Amount: ${fields['amount']}</h1>
// </div`);
} 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(`<form method="POST" action="/submit-expense" enctype="multipart/form-data">
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 form's action attribute is set to /submit-expense, but the server is listening for POST requests to /add-expense. This will cause the form submission to fail. Make sure that the form submits to the correct URL.

<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
Loading