Using Express.js to input and store information into a file

I am currently experimenting with writing data to a JSON file using Express.js. Specifically, I am looking to add a new JSON object to the file for each request made. As a beginner in this area, I am feeling quite overwhelmed and uncertain about what steps to take next. Below is the POST request code that I have put together so far. It may seem like a bit of a chaotic mess as I've gathered information from various sources to piece it together. Any guidance or assistance you can offer would be greatly appreciated!

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

});

Answer №1

Your code contains several bugs that need to be addressed. Firstly, avoid assigning res = { }. Secondly, remember to properly stringify the JSON data. It might also be helpful for you to review some Node.js tutorials to enhance your understanding. You can check out resources like https://www.tutorialspoint.com/nodejs/ or .

To meet your needs, consider using the following code snippet:

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.appendFileSync(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")
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with transitioning from TypeScript to React when implementing react-data-grid 7.0.0

I'm trying to add drag and drop functionality to my React project using react-data-grid, but I keep encountering a "TypeError: Object(...) is not a function" error. I have a TypeScript version of the file in the sandbox as a reference, but when I try ...

The use of cURL to send a POST array is resulting in an error message stating "Invalid

I am attempting to send an array of data from one domain to another using cURL. When I run the code below, I encounter the error message "Invalid argument supplied for foreach()". I have a suspicion that the issue lies with the array after it has been deco ...

Creating ParticleCloud instances in THREE.js

Hello, I am new to Threejs and still learning the ropes, so please bear with me if this question sounds basic. I have not had much experience working with particles. I am trying to figure out how to place points (particles) inside a custom geometry of tex ...

Transforming incorrectly formatted strings into JSONObjects: A step-by-step guide

The format of the JSON string received from the response is incorrect. I am trying to correct it but facing difficulties. The response obtained from a MongoDB related API is as follows: { "_id" : ObjectId("5ecd66aa9fd30b21cac18beb"), "_cla ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

Obtain data from an external XML source using jQuery

Hey there! I'm looking to scrape/parse some information from an external XML file hosted on a different domain and display it on my website. I attempted the following but unfortunately, it didn't work as expected: jQuery(document).ready(functio ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...

Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction wo ...

Convert all keys from underscore to camelCase for JSON objects using Circe

Source { "fName" : "foo", "lName" : "bar", "father" : { "fName" : "baz", "lName" : "bazz", } } Desired Output { "fName" : "foo", "lName" : "bar", "father" : { "fName" : "baz", "lName" : "bazz", } ...

Transmit a string of OCR text to the resAPI service

Currently, I am exploring the world of RestfulAPIs with Python. My goal is to extract text from a PDF using OCR and then send that text to a RestfulAPI to retrieve specific words along with their positions within the text. So far, I have been unsuccessful ...

After modifying the select option, the input field remains disabled

I successfully developed a self-contained code snippet that toggles the enable/disable state of input fields. It works flawlessly on my HTML page. Check it out below: Identification Type: <select name="Identification-Type" id="Identification-Type"& ...

Sending XML data from jQuery to two separate PHP scripts

After successfully sending XML data from jQuery via Ajax to the first PHP script, everything seems to be working fine. Here is a snippet of the jQuery - Ajax code: open('POST', 'get_and_send_XML.php', { xml: newXmlString1 }, '_b ...

To resolve the issue in Node, address the following error message: "User validation failed: username: Path `username` is required. Password: Path `password` is required."

I am currently in the process of creating a new user and verifying if the user's email already exists. If it does not exist, a new user is created and saved. Can anyone help me identify and correct the validation error I am encountering? I have attem ...

What is the best approach to managing errors from an Angular service within controllers?

As a newcomer to Angular, I am trying to figure out how to access error messages from a service within my controller. This is what my service looks like: admin.service('fileUpload', ['$http', function ($http) { this.uploadFil ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

A guide on incorporating a link to an external website once a Card is clicked in React JS

I have a code snippet for the Cards.js file that displays a card which links to the Services page on my website. I now want to add a link to an external website. How can I achieve this? Do I need to include an <a href= link in the Cards.js file? import ...

Moving the parent of a ThreeJS object to align with the geometry of its child

I am working with a 3D object that includes a cube mesh as a child. I am trying to adjust the position of the 3D object within the mesh in order to manipulate the pivot points of the cube mesh. You can find the code snippet on this codepen link. ...

Tips for automatically handling network errors with Apollo Client

Within my organization, we utilize an application that utilizes React, express, Apollo Server, and Apollo Client to showcase data from various sources. This app regularly updates the displayed data using a polling method. However, whenever I make code upda ...

What are the best practices for implementing Alertify in a Typescript project?

I'm relatively new to Angular2 so please bear with me. I attempted to implement Alertify.js in my Angular2 project for a custom dialog box, but I am encountering difficulties getting Alertify to work properly. Since I lack deep knowledge of JavaScrip ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...