Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation?

Below is the code snippet that has been edited:

export const data = require('./file.json');
export let DATA = data as Type[]; 

let temp = DATA;

app.post('/api/tickets', (req, res) => {
    // Load previous data into a JSON string
    const past_data = JSON.stringify(temp);
    // Load new data into a JSON string
    const new_element = JSON.stringify(req.params.formData)
    if (new_element !== "") {
        // Concatenate both strings into one JSON string and write it into fs
        fs.writeFile("./file.json",[past_data,new_element],(err) => {
            if (err) throw err;
        });
    }

    // Send the response back with the new data
    const new_data = JSON.parse([past_data,new_element].toString());
    res.send(new_data);
});

app.delete('/api/tickets/:id', (req, res) => {
    // Find the requested ticket based on id in the global temp
    const ticket = temp.find(t => t.id === (req.params.id));
    if (typeof ticket !== 'undefined') {
        const index = temp.indexOf(ticket);
        // Remove the ticket from the global temp
        temp.splice(index, 1)
    }

    // Create a JSON string out of the modified global temp
    const data_after_delete = JSON.stringify(temp);

    // Write the data directly into fs
    fs.writeFile("./file.json",data_after_delete,(err) => {
        if (err) throw err;
    });

    // Send the updated data back to the requester
    const new_data = JSON.parse(data_after_delete);
    res.send(new_data);
});


One object from the json file before any modification:

[
  {
    "id": "81a885d6-8f68-5bc0-bbbc-1c7b32e4b4e4",
    "title": "Need a Little Help with Your Site? Hire a Corvid Web Developer",
    "content": "Here at Wix we strive to support you with this community forum, API references, articles, videos and code examples. But sometimes you might need a little extra help to get your site exactly the way you want it. \nHire a developer from the Wix Arena, an online marketplace with top Corvid web developers from around the world. Submit your project details here, and we’ll find the right professional for you.",
    "userEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7ddc2d0f7d9d2c4d2c3d6db99d6d1">[email protected]</a>",
    "creationTime": 1542111235544,
    "labels": ["Corvid", "Api"]
  },

One object from the json file after being modified:

["[\"[\\\"[\\\\\\\"[{\\\\\\\\\\\\\\\"id\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"81a885d6-8f68-5bc0-bbbc-1c7b32e4b4e4\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"title\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"Need a Little Help with Your Site? Hire a Corvid Web Developer\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"content\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"Here at Wix we strive to support you with this community forum, API references, articles, videos, and code examples. Sometimes, additional assistance may be required to align your site precisely as desired. \\\\\\\\\\\\\\\\nHire a developer from the Wix Arena, an online marketplace featuring top Corvid web developers worldwide. Share your project details here, and we will connect you with the ideal professional.\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"userEmail\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e140b193e101b0d1b0a1f12501f18">[email protected]</a>\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"creationTime\\\\\\\\\\\\\\\":1542111235544,\\\\\\\\\\\\\\\"labels\\\\\\\\\\\\\\\":[\\\\\\\\\\\\\\\"Corvid\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"Api\\\\\\\\\\\\\\\"]},

Answer №1

For proper file handling, remember to use JSON.stringify when writing data to a file and JSON.parse when reading from a file (unless you are using require which handles parsing implicitly). It's important to manipulate your data as plain objects and arrays rather than as JSON strings to avoid damaging the structure.

export let DATA: Type[] = require('./file.json');
function save() {
    const jsonString = JSON.stringify(DATA);
//                     ^^^^^^^^^^^^^^^^^^^^^ call it only here
    fs.writeFile("./file.json", jsonString, (err) => {
        if (err) throw err;
    });
}

app.post('/api/tickets', (req, res) => {
    if (req.params.formData) {
        const new_element = req.params.formData; // JSON.parse() may be needed if it's a JSON string
        // manipulate array to add new element
        DATA.push(new_element);
        save();
    }
    // respond with updated data
    res.send(DATA);
});

app.delete('/api/tickets/:id', (req,res) => {
    // find requested ticket by id in global data
    const ticket = DATA.findIndex(t => t.id === (req.params.id));
    if (ticket !== -1) {
        // remove specified ticket from data
        DATA.splice(index, 1);
        save();
    }
    // send back updated data
    res.send(DATA);
});

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

Guidelines for incorporating role-based permissions in a React application

I am developing a MERN application that has various features catering to different roles. I need the ability to display specific data, navigation options, and divs based on the user's role while hiding these elements from others. It is important to no ...

Encountering an issue of TypeError in Backbone.js when trying to create a collection, specifically getting the error

Hey there, I'm diving into Backbone.js for the first time. While attempting to create a collection in Backbone, I encountered an error stating 'd.collection is undefined'. $(function(){ var MyModel = Backbone.Model.extend(); ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Unable to retrieve static files

I'm trying to incorporate the Jquery-ui datetime picker into my express js application, but I encountered a 404 error. <p>Date: <input type="text" id="datepick"></p> <link rel="stylesheet" type="text/css" href="stylesheets/jquery ...

How to open a new window in a separate desktop on macOS using Javascript

I am currently browsing my website on a Mac computer. I am interested in opening a new tab on the second desktop using Mission Control. Is this achievable? If so, could you please guide me on how to do it? After searching extensively online, I have been u ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...

Verify if the program is operating on a server or locally

My current project involves a website with a game client and a server that communicate via sockets. The issue I'm facing is how to set the socket url depending on whether the code is running on the server or my local PC. During testing and debugging, ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

Creating a separation between Mongoose data access code and pure data objects in Node.JS using Object-Oriented Programming

I've stumbled upon a design dilemma regarding Mongoose - could it be that my approach is off? In the traditional OOP fashion, I aim to create a User class. This class includes various attributes such as username, firstname, lastname, salt, and hash, ...

What is the best way to integrate the EJS view engine into a setup with Express and Webpack Dev Server?

I am currently facing an issue while trying to integrate ejs into a project that uses express and webpack dev server. The problem I am encountering is that even though I am passing my variables correctly, they are being loaded in this manner: Html Webpack ...

Is there a way to determine if the current path in React Router Dom v6 matches a specific pattern?

I have the following paths: export const ACCOUNT_PORTAL_PATHS = [ 'home/*', 'my-care/*', 'chats/*', 'profile/*', 'programs/*', 'completion/*', ] If the cur ...

The Angular module instantiation failed with the error message: "[$injector:modulerr] Failed to

Struggling with setting up basic AngularJS functionality for a project, especially when trying to include angular-route. Both components are version 1.4.8. My approach involves using gulp-require to concatenate my JS files. Here is my main javascript file: ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Is it possible to utilize PHP to dynamically add a URL, media, and description on Pinterest?

Check out this code snippet: <script type="text/javascript"> (function() { window.PinIt = window.PinIt || { loaded:false }; if (window.PinIt.loaded) return; window.PinIt.loaded = true; function async_load(){ var s = document.createElement("scrip ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

Unleashing the potential of extracting the value of a subsequent iteration while within the

Currently, I am facing a dilemma as I am unable to comprehend the logic required to design this algorithm. The problem at hand involves a sequence of images with arrows placed alternatively between each image. The structure appears as follows: Image -> ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Changing the address bar URL with Response.redirect in Node.js is not effective

I am currently using Express JS to build a web application. Within certain GET requests, I am redirecting the user to another page when they click a specific link: a( data-icon='home', data-transition='fade', data-role='button&apo ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...