problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet:


const response = await fetch('http://localhost:5000/api/users/signup',{
                method:'POST',
                headers:{
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({
                    name: data.get('name'),
                    email: data.get('email'),
                    password: data.get('password'),
                    image:data.get('image')
                  })
            });

Here is my full auth.js code for reference: https://pastebin.com/MHdDRtAX

Answer №1

One possible solution would be to utilize the FormData object in this scenario.

const inputField = document.querySelector('input[type="file"]');
const formDataBody = new FormData();

formDataBody.append('image', inputField.files[0]);
formDataBody.append('name', formData.get('name'));
formDataBody.append('email', formData.get('email'));
formDataBody.append('password', formData.get('password'));
// You can add more items as necessary

const serverResponse = await fetch(endpointURL, { method:'POST', body: formDataBody });

Answer №2

There seems to be a mismatch in the content type. When utilizing multer, it is necessary to specify

'Content-Type': 'multipart/form-data'
. The basic concept revolves around using the FormData object.

An illustrative example is provided below

const data = new FormData(event.target) 
const response = await fetch('http://localhost:5000/api/users/signup',{
                    method:'POST',
                    headers:{
                        'Content-Type': 'multipart/form-data'
                    },
                    body: data
                });

If you examine the network tab, you will notice form data with key-value pair. Ensure that the image is treated as a binary file in multer implementation.

For instance, refer to this code snippet using multer:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })
 
var app = express()    
app.post('api/users/signup', upload.single('image'), function (req, res, next) {
    // req.file refers to the `image` file
    // req.body holds the text fields, if any are present
})

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

Each time forEach is called, it increments the previous result by 1

My service returns a response containing the following data: {"id":157336,"results":[ {"id":"53db3c790e0a26189a000d09","iso_639_1":"en","key":"ePbKGoIGAXY","name":"Trailer 3","site":"YouTube","size":1080,"type":"Trailer"}, {"id":"550df44b925141355 ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

What is the best way to handle images overflowing a div

I am currently working on creating a carousel using React, where the content images are aligned horizontally. If I have 3 image tags within a div with a width of 1200px, how can I effectively control these images to ensure they fit within the container div ...

Having trouble executing a node module on a Windows system?

I am encountering an issue while trying to run npm run start-dev. I have been unable to resolve it on my own and could use some assistance. Here is a screenshot of the problem: https://i.stack.imgur.com/Qx243.png ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

angularjs dynamically display expression based on controller value

I'm not the best at explaining things, so I hope you all can understand my needs and provide some assistance here. Below is a view using ng-repeat: <div ng-repeat="item in allitems"> {{displaydata}} </div> In my controller, I have the f ...

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

Issue with ng-checked not detecting boolean values retrieved from local storage

I'm working on a code snippet in my controller where I have a checkbox in my HTML with "ng-checked="enterToSend" and "ng-click="enterToSendCheck()" attached to it. $scope.enterToSend = localStorage.getItem('enterToSend'); $scope.enterToSen ...

Tips for understanding nested JSON or array data structure?

My data is stored in a constant called translations and it looks like this: { "item-0": { "_quote-translation": "translation Data", "_quote-translation-language": "English", "_quote-trans ...

Effortless bug tracking in Chrome developer tools

When I'm debugging, I want the code to be displayed in Chrome browser (or another browser like Edge) exactly as it was written. Even when using pretty print, the code still appears unreadable. For example, a block of code written in my IDE: {provideD ...

gulp-open not functioning properly following the use of createWriteStream

I am utilizing gulp, gulp-eslint, and gulp-open to generate a report detailing ESLint outcomes. The linting and file creation processes function correctly; however, the task aimed at opening the file containing my report encounters issues. gulp.task(&apos ...

Tips on efficiently rebinding jQuery events to dynamically loaded content without having to manually do it for each event or class

Recently, I encountered an issue with my jQuery app where I needed to bind different functions to elements within one div dynamically. Specifically, I had a "delete-function" attached to all ".btn-delete" elements and an "add-function" linked to all ".btn- ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

How to Deactivate the Default Selection in React-Select

Having trouble with the focus in a React Select dropdown. The first item always gets focused when opening the dropdown, despite passing various props without success. I checked their GitHub for related issues around autofocus but couldn't find a solut ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...