Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
write/add data in file using express js

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

});

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda