I'm trying to write/add data in a json file (for example for each request, a new json is added in the json file) i am using Express.js. I am new to all of this so I really don't know what to do. I'm using a POST request, here's what i got so far. I know it's a big catastrophic mess, i scraped everything that could help me and gathered all of it. I'm just SO lost. Thanks for your help !
app.post('*/', function(req, res) {
res={
first_name: req.body.first_name,
last_name: req.body.last_name,
reponse1: req.body.reponse1,
reponse2: req.body.reponse2,
};
JSON.stringify(res);
var body = {
table: []
};
body.table.push(res);
filePath = __dirname + '/data.json';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.appendFile(filePath, body, function() {
res.end();
});
});
});
In your code, I see a lot of bugs. Firstly, you should not assign res = { }. Secondly, you stringify the JSON data like below. I will also suggest you to go through some tutorials of Node.js first. You can go through https://www.tutorialspoint.com/nodejs/ or https://www.codementor.io/nodejs/tutorial.
For your requirement, you can simply use following code:
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const fs = require('fs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/', function(req, res){
var body = {
first_name: req.body.firstName,
last_name: req.body.lastName
}
filePath = __dirname + '/data.json'
fs.appendFile(filePath, JSON.stringify(body), function(err) {
if (err) { throw err }
res.status(200).json({
message: "File successfully written"
})
})
})
app.listen(3000,function(){
console.log("Working on port 3000")
})