Click here to Skip to main content
15,916,949 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
this node.js controller does not save the size.name using utf-8 encoding Arabic characters, even though the rest of data is sent correctly to server with arabic encoding, i have tried to console log the size names and it reads them correctly but when i submit the form the arabic characters becomes unreadable.
JavaScript
  1  //contollers/menuItemsController.js
  2  const fs = require('fs');
  3  const path = require('path');
  4  const MenuItem = require('../../models/MenuItem');
  5  const Category = require('../../models/Category');
  6  const Size = require('../../models/Size'); 
  7  const dataPaths = require('../../config/data');
  8  const multer = require('multer');
  9  
 10  /////...
 11  function addItem(req, res) {
 12      upload.single('image')(req, res, function(err) {
 13          if (err instanceof multer.MulterError) {
 14              return res.status(500).json({ message: 'Opps! something happend when uploading the image' });
 15          } else if (err) {
 16           
 17              return res.status(500).json({ message: 'Opps! Internal Server Error' });
 18          }
 19          const { category, name, sizes } = req.body;
 20          const imageSrc = 'Frontend/img/' + req.file.filename;
 21          const sizePrice = req.body.sizePrice;
 22          const sizesWithPrices = [];
 23          Object.keys(sizePrice).forEach(sizeName => {
 24              const price = sizePrice[sizeName];
 25              if (price !== '') {
 26                  sizesWithPrices.push({
 27                      name: sizeName,
 28                      price: parseFloat(price)
 29                  });
 30              }
 31          });
 32      });
 33  }
 34          const newItem = new MenuItem(category, name, sizesWithPrices, imageSrc);
 35          fs.readFile(dataPaths.menuItems, 'utf8', (err, data) => {
 36              if (err) {
 37                  console.error('Opps! Error reading menu items file:', err);
 38                  return res.status(500).json({ message: 'Internal Server Error' });
 39              }
 40  
 41              const menuItems = JSON.parse(data);
 42  
 43              menuItems.push(newItem);
 44  
 45              fs.writeFile(dataPaths.menuItems, JSON.stringify(menuItems, null, 2), 'utf8', (err) => {
 46                  if (err) {
 47                      console.error('Opps! Error updating menu items file:', err);
 48                      return res.status(500).json({ message: 'Internal Server Error' });
 49                  }
 50                  res.redirect(`/admincp/menuitems?token=${req.query.token}`);
 51              });
 52          });
 53      });
 54  }
 55  /////...

HTML
<!-- views/admincp/menuData/additem.ejs -->
<div class="card-body">
    <form action="/admincp/menuitems/add?token=<%= token %>" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
        <div class="mb-3">
            <label for="category" class="form-label">الفئة</label>
            <select class="form-select" id="category" name="category" required>
                <% categories.forEach(category => { %>
                <option value="<%= category.name %>"><%= category.name %></option>
                <% }); %>
            </select>
        </div>
        <div class="mb-3">
            <label for="name" class="form-label">الاسم</label>
            <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="mb-3 d-flex flex-column">
            <label class="form-label">الأحجام</label><br>
            <% sizes.forEach(size => { %>
            <div class="form-check">
                <input class="form-check-input size-checkbox" type="checkbox" id="<%= size.name %>" name="sizes[]" value="<%= size.name %>">
                <label class="form-check-label" for="<%= size.name %>"><%= size.name %></label>
                <input type="text" class="form-control size-price" id="<%= size.name %>-price" name="sizePrice[<%= size.name %>]" placeholder="سعر الحجم" pattern="[0-9]+(?:\.[0-9]+)?" title="يرجى إدخال أرقام فقط" style="display: none;">
            </div>
            <% }); %>
        </div>
        <div class="mb-3">
            <label for="image" class="form-label">اختر صورة (PNG, JPG, JPEG)</label>
            <input type="file" class="form-control" id="image" name="image" accept=".png, .jpg, .jpeg" required>
        </div>

        <button type="submit" class="btn btn-primary">إضافة</button>
    </form>
</div>


What I have tried:

console logged the received data, it loads correctly, I included UTF-8 encoding while posting the request to server.
Posted
Updated 4-Apr-24 22:49pm
v2
Comments
Pete O'Hanlon 4-Apr-24 16:12pm    
What am I missing here? I don't see any database updates in there.
Richard Deeming 5-Apr-24 4:52am    
The closest thing I can see to a "database" is reading and writing to a JSON file. This is not a "database" in any real sense.

1 solution

My suggestion here mirrors the advice I would give anyone who has a bug in their software. What you need to do is debug your node service. Set breakpoints inside the code and check what data you receive when the call is made.

To enable node debugging, try running your service from vscode using the techniques documented here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900