#Problem with Adding Data to the JSON-File

44 messages Β· Page 1 of 1 (latest)

ebon sage
#

πŸ‘‹ Hello, I need help with my website. I have an HTML-Form and a JSON-File with data. When I fill out the form and press the button to add new data into the JSON file, I get the following error codes:

Console:
`- "Failed to load resource: the server responded with a status of 404 (Not Found)"

  • "Error adding product: Error: Failed to add product
    at data.js:43:23"
  • "Server error: Failed to add product (anonymous) @ data.js:53"`
long dew
prisma hazelBOT
#
To help us help you, when asking for help, tell us the following:
πŸ’ πŸ’ πŸ’ 
  • Expectations! What did you expect your code to do? What did it actually do?
  • Errors! If your code produced an error, paste the error message for us to see!
  • Code! We can't help you if you don't show us the code that you're having trouble with. No screenshots -- use code blocks instead please (!!help.codeblocks).
  • Libraries! If you're using a library, tell us the library name.
ebon sage
#

Thanks for your assistance, How can I share my Code? Because its says "too long" to share

ebon sage
haughty spade
ebon sage
#

Main/
β”‚
β”œβ”€β”€ public/
β”‚ β”œβ”€β”€ css/
β”‚ β”œβ”€β”€ data/
β”‚ β”‚ └── .json
β”‚ β”œβ”€β”€ images/
β”‚ β”‚ └── products/
β”‚ β”‚ └── (all images)
β”‚ β”œβ”€β”€ js/
β”‚ β”‚ β”œβ”€β”€ script.js
β”‚ β”‚ β”œβ”€β”€ db.js
β”‚ β”‚ └── data.js
β”‚ β”œβ”€β”€ dashboard.html
β”‚ └── index.html
β”‚
└── server/
└── server.js


#

data.js:

// loading JSON-File
document.addEventListener("DOMContentLoaded", function () {
// fetching JSON-File
fetch('data/shoes.json')
.then(response => response.json())
.then(data => {
// JSON-File -> JSON-Model
products = data.shoes;

        // Display Products
        displayProducts(products);
    })
    .catch(error => console.error('Error loading products:', error
    ));
// Catching Form
const addProductForm = document.getElementById('add-product-form');
addProductForm.addEventListener('submit', function (event) {
    event.preventDefault(); // Prevent Default-Event

    // Collect FormData
    const formData = new FormData(addProductForm);

    // Convert Data into JSON-Format
    const jsonData = {};
    formData.forEach((value, key) => {
        jsonData[key] = value;
    });

    // Send POST-req.
    fetch('/add-product', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(jsonData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Failed to add product');
        }
        // Alert - Product successfully added!
        alert('Product successfully added!');
        // additional logic, e.g. reset the form
    })
    .catch(error => {
        console.error('Error adding product:', error);
        alert('Error adding the product');
        // The error is displayed more precisely here
        console.error('Server error:', error.message);
    });
});

});

// Iterate through the products and insert into the container element
products.forEach(product => {
const productCard = createProductCard(product);
productContainer.appendChild(productCard);
});
};

#

i can read the data and display them but i cant add new data into that


long dew
#

Can you share the code of the POST request at /add-product?

haughty spade
#

I'm not quite sure what you're trying to achieve, but it looks as if your JSON is stored locally/clientside and not serverside.
Then you could use the FS module to read the JSON, parse the data to an array, push the new data-record to that array and then overwrite the JSON with the new data-array

#

or does your server handle your requests to the JSON? Then I'd recommend to search the mistake there (and check for error messages)

ebon sage
# long dew Can you share the code of the POST request at /add-product?

if u meant the server.js...here is the code:
`const express = require('express');
const fs = require('fs');
const path = require('path');
const fileUpload = require('express-fileupload');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('./public'));
app.use(fileUpload());

// Reading Data to JSON
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './public/dashboard.html'));
});

// POST-Req. - Adding Data
app.post('/add-product', (req, res) => {
const newProduct = req.body; // New Product info - Formular

// Reading Data - JSON-File
fs.readFile('./public/data/shoes.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return res.status(500).send('Error reading file');
}

const products = JSON.parse(data); // Convert JSON to JavaScript-Object
products.shoes.push(newProduct); // Add the new product

// write the new into the JSON-File
fs.writeFile('./public/data/shoes.json', JSON.stringify(products, null, 2), 'utf8', (err) => {
  if (err) {
    console.error('Error writing file:', err);
    return res.status(500).send('Error writing file');
  }
  
  // Successful msg
  res.status(200).send('Product added successfully');
});

});
});

// Server stuff
app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});`

#

(btw im kinda new to all of this) πŸ‘Ύ

ebon sage
long dew
#

Does your JSON file update after the function runs?

ebon sage
#

What do you mean by that...

#

and what function

long dew
#

When you fill out the form and press the button to add new data into the JSON file, does the data get added into the JSON file?

#

Your server code is not aligned with ur client code.
In the server, on success you are sending status 200 and the success msg.
In the client, you are checking if response.ok is true. If not ok then you are logging errors.

ebon sage
ebon sage
#

Because in my Form there a numbers, strings, etc and an picture which can be uploaded

#

Like This

long dew
#

First, need to figure out where your server code is failing.
Add console log statements to figure out where your code is crashing.

haughty spade
#

You can't store an image directly in a JSON. Do you process the image data anywhere?
Does your POST from the form work if you remove the image input?

ebon sage
#

All pictures are currently stored in a local directory, and the JSON data contains the image paths as strings.

I created a test website where I tested all of this, and everything worked as expected.

ebon sage
haughty spade
#

what is the main difference between your test website and the real website?

ebon sage
#

the test website shows only the products/list (with less data)

haughty spade
#

My assumption is that the path to your local JON might be wrong/not accessible for the "real" website.

haughty spade
ebon sage
#

nope, works perfectly fine

haughty spade
#

hmm... if it worked perfectly fine it should bring the expected result, not? πŸ€”

ebon sage
#

yh it does on the test website, but not on the real website...I copied the exact code and it still didnt work

haughty spade
#

I definitely would add some console.logs in your server.js where the form data get received and handled

ebon sage
#

I don't understand the part with: *"where the form data get received and handled" *

haughty spade
#

in the POST request

long dew
ebon sage
#

🀝 Okay it worked...Thank you guys so much for helping me out peepostonks

long dew
#

What was the issue?

ebon sage
# long dew What was the issue?

I improved the test version of the website and it worked. But when I copied everything to the main version, it didn't work. The error logs showed that the file path was correct, but the file name was different.