Use AJAX to send data parameters and files to a backend server running on Node.js

I've encountered an issue with my code and I'm struggling to pinpoint the exact problem.

In this particular section involving AJAX, I am trying to send a file from a form along with an argument to my node.js server:

var layerID = 2;
var formData = new FormData($("#formid")[0]);
formData.append('layer', layerID);
  $.ajax({
     url: "http://localhost:3000/file-upload",
     type: 'POST',
     data: formData,
     cache: false,
     contentType: false,
     processData: false
  });

Additionally, there is this part using Express which is supposed to accept the file and the argument:

app.use(bodyParser.urlencoded({
   extended: false
}))

app.post('/file-upload', function (req, res) {
  console.log('params: ' + req.params);
    console.log('body: ' + req.body);
    console.log('query: ' + req.query);
  upload(req, res, function (err) {
    if (err) {
      errorHandler
      return
    } else {
      successHandler
    }
  })
})

The issue lies in the fact that while the file is being received correctly, the 'layer' argument is not being received by my node.js server.

Answer №1

When POSTing multipart data, make sure you have the appropriate body parser set up.

Refer to the documentation for the body parser:

The current body parser is not equipped to handle multipart bodies, as they are complex and often large. Consider using one of the following modules instead:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer

Answer №2

To efficiently parse multipart data, you can utilize packages such as multiparty. There are various other packages available for this task.

Server-Side Code

const multiparty = require('multiparty');

         // Define POST route
 app.post('/file-upload', function (req, res) {
     const form = new multiparty.Form();

     form.parse(request, async (error, fields, files) => {
       if (error) throw new Error(error);

       try {
         const path = files.file[0].path;
         const layer = fields && fields.layer && fields.layer[0]
         const buffer = fs.readFileSync(path);

         // TODO 

         return response.status(200).send(data);
       } catch (error) {
         return response.status(400).send(error);
       }
     });
 }

You can retrieve information from fields in this manner.

Client-Side Code

const formData = new FormData();
formData.append('file', fileObj);

uploadHandler(formData) // this function will initiate an API call

With this setup, you can easily access files.file[0]

Answer №3

The resolution emerged when I decided to relocate my request body log within the upload function, accessing it as shown here: console.log("layer: " + req.body['layer']);

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

Immediately Invoked Function Expression in Javascript

const user = { name: "John", age: 30, lastName: "Smith" } (({name, lastName}) => { console.log(name); console.log(lastName); })(user); An error occurred: {(intermediate value)(intermediate value)(intermediate value)} is not function ...

Tips on launching a new tab in a web browser from a ctools modal form within Drupal 7

I am developing a module that includes various forms, some of which are modal forms utilizing ctools. On one particular modal form, I have a button that is supposed to open a PDF in a new browser tab, but it seems to be encountering an AJAX error. Here is ...

Using a conditional statement in conjunction with the jQuery .animate function

As a complete novice with Javascript and jQuery, I am attempting to animate a div only if a specific variable is true, but unfortunately, it's not functioning as expected. Can someone offer guidance on how to resolve this issue? Below is the code I h ...

JavaScript Indexed Array Names: Managing Arrays with Indices

I have a collection of arrays named "list0" through "list7" which have been explicitly defined. My goal is to include each of these arrays as elements in an existing array, creating a 2D array of these defined arrays. How can I reference each 'list&a ...

Warning in Google Script editor

Currently, I am working on creating some quick scripts to manipulate spreadsheets in my Google Drive. However, I am cautious about the script unintentionally running and making changes to data before I am ready or executing multiple times after completing ...

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

Manipulating CSS for a certain ID that is applied to multiple elements with the help of JQuery

I am attempting to conceal all div elements except the initial one within a specific ID. Despite my efforts to create a custom jQuery script, it does not appear to be functioning. $("div.hero-featureSwap:not(:first)").css({display:none}); Is this scr ...

Execute an AJAX request and dynamically update the page when the button is clicked simultaneously

Hello everyone, I'm a beginner in ajax and I'm encountering an issue with executing JavaScript when a button is clicked. What I'm trying to achieve is, when the button is clicked, I want to run an ajax function to call a PHP script for query ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

Webster Barron code script

I'm attempting to replicate the concept of this video https://www.superhi.com/video/barron-webster using text, but I am encountering difficulties in achieving the desired effect. The design text is currently overlapping my name and displaying in rev ...

Exploring the power of Node.js and underscore.js for advanced templating capabilities

My question is quite simple. I am using Node.js with Underscore as the templating engine, all within the Expressjs framework. I am attempting to create partials similar to other programming languages: <% include('header') %> <body id ...

Handling the success of a $.ajax function when encountering an unconventional HTTP status code

We've developed a RESTful server API and decided to return a 204 (No Content) status code with an empty response for DELETE requests. I am using jQuery to make the DELETE call with a success handler specified: jQuery.ajax({ type:'DELETE&apos ...

The save and cancel button are experiencing technical difficulties and are currently non-functional

After creating an application in AngularJS to add and remove popup modals, I encountered an issue where the saved data was returning as undefined, and the cancel functionality was not working properly. Check out the JSFIDDLE here If anyone has any soluti ...

Contrast two JSON data sets

Similar Question: Object comparison in JavaScript Is there a way to compare two JSON objects and identify any differences in the data they contain? Update After going through the feedback, some additional details are required. A JSON object is d ...

Managing numerous Ajax requests during pagination

retrieve information : <div class="events"> @include('data.php') </div> here is the implemented code : <script> $(document).ajaxStop(function () { $('#loadingSpinner').hide(); }); $(document). ...

Could you explain why my code is not functioning as intended when I attempt to modify the class of a specific element?

I've been trying to change the class of a specific <li></li> element, but none of the methods I've attempted seem to be working. Could you please help me figure out why my code isn't functioning as expected? <script type="tex ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

What is the best way to fill the MongoDB post schema with every comment for the post?

I have created two schemas, one for posts and another for comments. const PostSchema = new Schema( { title: { type: String, required: true }, text: { type: String, required: true }, author: { type: Schema.Types.ObjectId, ref: 'User' ...

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

What is the functionality of the cookie-session middleware in Express.js?

Could someone explain the underlying concepts of cookie-session in expressjs to me? When we store something in session, like this: req.session.myName = "Manas Tunga"; Where is this session data actually stored? Is it in client-side session cookies or in ...