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

Having trouble with jQuery on my webpage

Looking for assistance with a technical issue I'm facing... I am currently working with AngularJS and have integrated jQuery into my project. However, I've encountered an issue where the jQuery code is not functioning as expected on the HTML pag ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

The Forge Viewer's getState() function is providing inaccurate values for individual items

In our Angular application, we have integrated the latest version of Forge Viewer and are storing the current state of the viewer in our database for future restoration. After thorough testing, we discovered that isolated nodes are not being saved correct ...

Can you come up with a catchy one-liner for an array that contains all the elements of the arrays that came

I am currently working with the array [1,2,3,4,5,6,7,8,9] My goal is to achieve [ [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], ... ] I envision the desired outcome as const var = array.reduce **using some form of black magic** I ...

Height Miscalculation: Chrome and FF encounter window dimension

There is a large application with numerous pages. When I use the console to execute console.log($(window).height()) on any page within the application, it returns the expected result: the height of the window, not the document. For instance: $(window).he ...

Is there a method to access the variable name of v-model from a child component in the parent component?

In the scenario below, I am customizing a vue radio component and using the model option to retrieve the v-model value, which is expected to be a string '1'. Is there a way for me to access its variable name 'radio1' in the child compon ...

The issue of Next.js redux useSelector causing HTML inconsistency

Currently, I am utilizing Next.js for the development of a React application. In order to manage the state, I have integrated redux along with redux-toolkit. A peculiar error has surfaced in the console with the message: Warning: Did not expect server H ...

Create a bookmark system on an HTML page by utilizing the existing heading tags and implementing Javascript

Looking to implement a bookmark system using the headings within my HTML document, based on heading hierarchy. Unfortunately, my attempts have not been successful so far. https://i.stack.imgur.com/CdXjw.png I envision my bookmarks looking something like t ...

Vue Router is not updating the router view when the router link clicked is embedded within the view

I have a section called Related Content located at the bottom of my posts page, which displays other related posts. When I click on the Related Content, I expect the router to update the page. However, it seems that although the URL changes, the view does ...

Merge these two NPM packages together

Two npm projects exist: web-api (a library) and UI. The web-api utilizes gRPC-web to interact with the backend before converting it into a simple JavaScript object. In the UI, Vue.js is used in conjunction with web-api. Objective: merge these two project ...

Would you suggest using angularjs for authentication in large-scale applications?

As I continue to learn and utilize the AngularJS framework, I have noticed that while some of its features are impressive, some key aspects make it challenging for authentication-based applications. For example, let's consider a scenario where a webs ...

Error encountered while using jQuery AJAX to fetch SVG file: 'Invalid format'

For a while now, I have been using various SVGs from Inkscape and loading them into a specific container element with the .load method. Recently, I decided to switch things up and use AJAX's .get method instead, primarily because I wanted to prepend t ...

Removing a select menu in Discord.js once a selection has been made

Currently in the process of creating a ticket tool that utilizes a select menu for choosing a topic const row = new MessageActionRow() .addComponents( new MessageSelectMenu() .setCustomId(`select_menu`) .setPlac ...

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...