1

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();
    });
});

});

2
  • What happens when you run it. is there any error, whats in console? Commented Apr 16, 2017 at 11:02
  • no error on the console but i'm using it on a chatbot and they said "Unable to parse JSON" , i think it will work fine with the answer below though ! thank you so much Commented Apr 16, 2017 at 17:19

1 Answer 1

1

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")
})

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much ! now i receive the error message "Unable to parse JSON" what do you think I should change ?
i can't, there's no error on the console, only when i launch my bot and send a request to my server it gives me that message. But I think it's an issue related to the plateform i use...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.