Reputation: 141
From what I know I should modify the post function, but I don't know exactly how to add the new json object to the JSON file. What I would want to happen to the JSON file after the post function is having a 4th element, just like the others already existing 3.
The JSON file:
[
{
"author": "John",
"comment": "How are you"
},
{
"author": "Alex",
"comment": "Hello"
},
{
"author": "Maria",
"comment": "Good morning"
}
]
Node js:
const express = require('express')
const app = express()
const port = 3000
var someObject = require('./bd.json')
app.use(express.json())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, access-control-allow-origin")
next();
});
app.get('/', (req, res) => res.send('Hello World!'))
app.post('/', (req, res) => {
res.send({Status: 'OK'});
})
app.get('/comments', (req, res) => {
res.send(someObject);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
EDIT: I added the HTML part HTML:
<html>
<head>
<script>
window.onload = function(){
getComments();
}
function getComments(){
fetch("http://localhost:3000/comments")
.then((data) => { return data.json() })
.then((json) => displayComments(json))
}
function displayComments(data){
let responseArea = document.getElementById('responseArea');
for (let i = 0; i<data.length; i++){
let authorName = document.createElement('P');
authorName.innerText = data[i]["author"];
let commentContent = document.createElement('P');
commentContent.innerText = data[i]["comment"];
let someRespone = document.createElement('DIV')
someRespone.appendChild(authorName)
someRespone.appendChild(document.createElement('BR'))
someRespone.appendChild(commentContent);
someRespone.style.border = "1px solid black";
responseArea.appendChild(someRespone);
}
}
function sendInformation(){
let name = document.getElementById('name').value;
let comment = document.getElementById('comment').value;
fetch("http://localhost:3000", {
method: 'POST',
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify({name: name, comment: comment})
}).then((data) => {
return data.json()
}).then((json)=>{
if(json.Status === 'OK'){
document.getElementById('responseArea').innerText='Information receieved';
} else {
document.getElementById('responseArea').innerText='Information was not received';
}
console.log(json);
})
}
</script>
</head>
<body>
Name:
<input id='name' type='text' placeholder="name"/>
</br>
Comment:
<textarea id='comment'> </textarea>
<input type='button' value="Send" onClick="sendInformation()">
<div id='responseArea'></div>
</body>
</html>
Upvotes: 2
Views: 1153
Reputation: 10604
You can use node fs
module to read and write your json data into json file.
First you need to read all the comments from the file which includes old comments.
Then convert that to Object
and append the new comment and save.
Sample Code
const fs = require('fs');
const path = require('path');
const express = require('express')
const app = express()
const port = 3000
const someObject = path.join(__dirname, 'bd.json');
app.use(express.json())
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, access-control-allow-origin")
next();
});
app.get('/', (req, res) => res.send('Hello World!'));
app.post('/', (req, res) => {
/* Sample code */
fs.readFile(someObject, { encoding: 'utf-8' }, function (err, data) { // Read the old comments
if (!err) {
const comments = JSON.parse(data);
if (comments && comments.length > 0) {
comments.push(req.body);
} else {
comments = [];
}
fs.writeFile(someObject, comments, (err) => { // Write back the all comments with the newly added comment.
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('saved!');
res.send({ Status: 'OK' });
});
} else {
console.log(err);
throw err;
}
});
/* Sample code */
})
app.get('/comments', (req, res) => {
res.send(someObject);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Upvotes: 0
Reputation: 1922
You have to read the file first convert it to an object then back to json and write to the file system. Here is an example with your code.
app.post('/', (req, res) => {
fs.readFile('file.json', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
let obj = JSON.parse(data);
obj.push({
author: req.body.author,
comment: req.body.comment
}); //add some o
let json = JSON.stringify(obj);
fs.writeFile('file.json', json, 'utf8', (err) => {
if (err) {
throw err
}
console.log('the file has been saved')
res.send("succes")
});
}
})
})
Upvotes: 3