Question:
Nodejs Error Solved: "MulterError: Unexpected field" using NodeJs

If you want to save an image in an SQL db but it gives an MulterError then you should change the image to file on the frontend side:


let forms = document.querySelectorAll('form');

let divisionIdInput = form.querySelector('#divisionIdInput');

let imageInput = form.querySelector('#imageInput');


const formData = new FormData(); // Create a FormData object


formData.append('file', imageInput.files[0], imageInput.files[0].name);


const divisionId = divisionIdInput.value;

fetch(`/divisionData/${divisionId}`, {

  method: 'POST',

  body: formData, // Let the browser set the correct Content-Type and boundary

})

  .then(response => {

    if (!response.ok) throw new Error('Error inserting data');

    return response.text();  // Read the response as text

  })

  .then(responseText => {

    console.log('Response from server:', responseText);

  })

  .catch(error => {

    console.error('Error:', error);

  });


and also you should wrap your express function in try-catch scope, to find problems in the backend side:


app.post('/divisionData/:divisionId', upload.single('image'), (req, res) => {

    try{

    const image = req.file.buffer;

    const contentType = req.file.mimetype;

    const { divisionId } = req.body;


    // Check if any of the values are null

    if (divisionId === undefined || image === undefined) {

        res.send('All fields must have values.');

        return;

    }


    const insert_user_query = "INSERT INTO divisions (divisionId, image, contentType) VALUES (?, ?, ?)";

    const values = [divisionId, image, contentType];

    conn.query(insert_user_query, values, (err, result) => {

        if (err) {

            console.error("Database error:", err);

            return res.json({ error: "Failed while inserting data into database! Try to send files again." });

        }


        return res.json({ success: true });

    });

    }catch(err){

      return  res.status(500).json({ error: `Internal Server Error ${err}` });

    }

});


Answered by:> milad shiriyan

Credit:> StackOverflow


Suggested Blogs:

>How to show encrypted user id in URL in Laravel?

>How to fix Laravel LiveWire listener?

>Run Laravel Project to Active Local Server

>How React hooks Completely replace redux?

>How to access the state using Redux RTK in the React Native app?

>How to Build a Python GUI Application With WX Python

>How to Build a RESTful API Using Node Express and MongoDB- Part 1

>How to build an Electron application from scratch?

>How to build interactive_graphviz in Python

>How to change the project in GCP using CLI command

>How to create a line animation in Python?


Nisha Patel

Nisha Patel

Submit
0 Answers