-
Notifications
You must be signed in to change notification settings - Fork 240
solution #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
solution #187
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,47 @@ | ||
| '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((request, response) => { | ||
| if (request.url === '/add-expense' && request.method === 'POST') { | ||
| const chunks = []; | ||
|
|
||
| request.on('data', (chunk) => { | ||
| chunks.push(chunk); | ||
| }); | ||
|
|
||
| request.on('end', () => { | ||
| try { | ||
| const parsedData = JSON.parse(Buffer.concat(chunks).toString()); | ||
|
|
||
| if (!parsedData.amount || !parsedData.title || !parsedData.date) { | ||
| response.statusCode = 400; | ||
| response.end('Invalid data'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const db = path.join(__dirname, '../db/expense.json'); | ||
| const stringifiedData = JSON.stringify(parsedData); | ||
|
|
||
| fs.writeFileSync(db, stringifiedData); | ||
|
|
||
| response.statusCode = 200; | ||
| response.setHeader('Content-Type', 'application/json'); | ||
| response.end(JSON.stringify(parsedData)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The task requires returning an HTML page that contains the JSON data. Currently, you are sending a response with the |
||
| } catch { | ||
| response.statusCode = 400; | ||
| response.end('Invalid data'); | ||
| } | ||
| }); | ||
| } else { | ||
| response.statusCode = 404; | ||
| response.end('Not Found'); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| module.exports = { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This implementation overwrites the
expense.jsonfile with every new request. As a result, only the last submitted expense will be saved. To store all expenses, you should first read the existing content of the file, parse it as an array, add the new expense object to that array, and then write the updated array back to the file.