Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
23 changes: 23 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"license": "GPL-3.0",
"devDependencies": {
"@mate-academy/eslint-config": "latest",
"@mate-academy/scripts": "^1.8.6",
"@mate-academy/scripts": "^2.1.3",
"axios": "^1.7.2",
"eslint": "^8.57.0",
"eslint-plugin-jest": "^28.6.0",
Expand Down
95 changes: 93 additions & 2 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,99 @@
'use strict';

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

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Form</title>
</head>
<body>
<h1>Submit expense</h1>
<form method="POST" action="/add-expense">
<label>
Date
<input type="date" name="date" required />
</label>
<label>
Title
<input type="text" name="title" required />
</label>
<label>
Amount
<input type="number" name="amount" required />
</label>
<button type="submit">Submit</button>
</form>
</body>
</html>`;

res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);

return;
}

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 task requires showing an HTML form. There is no GET handler to serve the form (e.g. GET '/' returning an HTML page with inputs for date, title and amount). Add a route that serves the form HTML.

let body = '';
const contentType = req.headers['content-type'] || '';

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

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

try {
if (contentType.includes('application/x-www-form-urlencoded')) {
expense = querystring.parse(body);
} else {
expense = JSON.parse(body);
}
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(['Invalid request payload']));
Comment on lines +60 to +61
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

When parsing fails you return a 400 with application/json. Parsing errors should still return a 400 but as an HTML page (Content-Type: text/html) with a clear, user-friendly error message so the server doesn't return raw JSON to a browser.


return;
Comment on lines +59 to +63
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 parsing error branch currently returns JSON. Per checklist items #6 and #12 you must keep the 400 status but send an HTML page (Content-Type: 'text/html; charset=utf-8') with a clear human-readable message such as "There was a problem reading your form data." Replace the JSON response here with such an HTML response.

}

if (expense.date && expense.title && expense.amount) {
const fs = require('fs');
const path = require('path');
const dataPath = path.resolve(__dirname, '../db/expense.json');

fs.writeFileSync(dataPath, JSON.stringify(expense, null, 2));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(expense));
Comment on lines +72 to +73
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 response for a successful save is sent with Content-Type: application/json and raw JSON. The requirement asks to "return an HTML page with well formatted JSON" — change the response to text/html and embed pretty-printed JSON (for example JSON.stringify(expense, null, 2)) inside an HTML structure such as <pre>...</pre>.

Comment on lines +72 to +73
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 successful POST response currently sends 'Content-Type: application/json' and raw JSON. The spec requires 'Content-Type: text/html' and an HTML document embedding JSON.stringify(expense, null, 2) (for example inside a

) so the browser shows formatted JSON.

Comment on lines +71 to +73
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

After writing the expense file the handler returns application/json. Per checklist items #5, #11 and #16 the successful POST /add-expense response must use Content-Type: 'text/html' and return an HTML document that embeds JSON.stringify(expense, null, 2) (for example inside a <pre>). Replace this JSON response with an HTML document containing the pretty-printed JSON.

} else {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(['Missing required fields']));
Comment on lines +75 to +76
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Error responses (400/404) are returned as application/json. Consider returning HTML pages for errors or at least consistent responses with the task (the main success response should be an HTML page). Also provide clearer error information when required fields are missing.

Comment on lines +74 to +76
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 'missing required fields' branch responds with application/json. Change this to an HTML response (Content-Type: text/html) that explains which required fields are missing (or at least a clear human-readable message) to match the app's main behavior.

Comment on lines +74 to +76
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 "missing required fields" branch returns JSON. Per checklist item #7 change this to an HTML page (Content-Type: 'text/html; charset=utf-8') that clearly explains which fields are missing (for example: <p>Missing required fields: date, title, amount</p>). Consider computing the missing field names from expense and inserting them into the message.

}
});
} else {
const notFoundHtml = `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Not Found</title>
</head>
<body>
<h1>404 - Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</body>
</html>`;

res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(notFoundHtml);
}
});
}

module.exports = {
Expand Down
Loading