Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours.

My goal is to upload an image file along with stringified coordinates to crop the image on the server-side.

Below is my client-side code:

      var formdata = new FormData();
      formdata.append("file", file);
      formdata.append("coords", JSON.stringify(coordInfo));

      var xhr = new XMLHttpRequest();
      if ( xhr.upload ) {

            // for handling the progress of the upload
            xhr.upload.addEventListener('progress',progressHandlingFunction, false); 
      }
      xhr.onreadystatechange = function(e) {
          if ( 4 == this.readyState ) {
              console.log(['xhr upload complete', e]);
          }
      };
      xhr.open('post', '/changeProfilePicture', true);
      xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
      xhr.send(formdata);

The relevant Express middleware I'm using includes:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/changeProfilePicture', multipartMiddleware);

In my route, I'm simply logging values to check if they were passed correctly:

    console.log("req.body.file");
    console.log(req.body.file);
    console.log("req.body.coords");
    console.log(req.body.coords);
    console.log("req.body.formdata");
    console.log(req.body.formdata);
    console.log("req.body");
    console.log(req.body);

When checking in Chrome, the request payload appears as follows:

------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="file"; filename="monkey_mad.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="coords"

{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
------WebKitFormBoundary6A5RYri63wa7LqdB--

However, on the server-side, only the coords are being displayed:

17:53:19 web.1  | req.body.file
17:53:19 web.1  | undefined
17:53:19 web.1  | req.body.coords
17:53:19 web.1  | {"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
17:53:19 web.1  | req.body.formdata
17:53:19 web.1  | undefined
17:53:19 web.1  | req.body
17:53:19 web.1  | { coords: '{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}' }

I have tried numerous client-side and server-side variations to make this work. Previously, I used an AJAX XHR Request and busboy on the server side, which resulted in a broken image when retrieved.

For reference, here's the unresolved Stack Overflow question related to that issue: here.

Now, I've switched to a non-AJAX XHR approach and am using connect-multiparty for parsing, but the problem still persists.

Answer №1

Make sure to check for the presence of files in req.files rather than req.body.

On a different note, be aware that req.body.coords appears to be a JSON string, not an object. You will need to use JSON.parse to convert it into an object, just to be safe and cover any oversight.

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

Organize WordPress loop posts based on tags in real-time

I have integrated a custom loop into my WordPress custom blog page to display all my posts. Here's how I did it: <section class="container blog-article-actu"> <div class="row"> <?php $the_query = ne ...

The powerful combination of ES6 and sequelize-cli

How can I execute sequelize migrations and seeds written in ES6? I attempted to use babel-node, but encountered a strange error. Command node_modules/babel-cli/lib/babel-node.js node_modules/sequelize-cli/bin/sequelize db:seed Error node_modules/b ...

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...

Validating American phone numbers using regular expressions

I came across a Javascript regex that is used to validate the different formats in which US phone numbers can be written. However, there seems to be an issue with it: it fails to match the second rule within this specific group: The first group of three ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...

Guide to importing a JavaScript module as any type without using a declaration file (d.ts)

Looking to bring a js module into my ts app. Is there a way to achieve this without creating a d.ts file? If not, how can it be declared as any in the d.ts file? Currently using //@ts-ignore to ignore the error. Appreciate any help! ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward: class MyController extends Controller { public function list() { return response()->json(['a' => 'hello']); } } When I access the ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

Error in Bcrypt: Invalid parameters detected - expecting a string but received undefined

While attempting to establish a login endpoint and send an authentication token, I encountered some issues. When sending a request to create a user, everything works smoothly. However, when sending a request for login authentication, I receive an internal ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

Retrieve information from both the client and server sides within NextJS

Looking to integrate a third-party API for data fetching in certain components within my NextJS project. The goal is to have the server pre-render these components with the API for optimal SEO benefits, but also enable client-side fetching of component pro ...

Transforming Material UI into a class-based component

How can I transform a React function into a class? I'm having trouble understanding how to adjust const { classes } = props; in a function to work within a class. You can find an example button function from Material UI here: import React from &apos ...

Using *ngFor with a condition in Angular 4 to assign different values to ngModel

I am new to Angular 4 and encountering an issue with using *ngFor in conjunction with HTML drop-down select and option elements. My categories array-object looks like this - categories = [ { id:1, title: 'c/c++'}, { id:2, title: 'JavaScri ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Exploring the capabilities of React testing-library for interacting with the DOM within a React application

I've been working on developing custom developer tools after finding inspiration from Kent C Dodds' insightful article here. One of the challenges I encountered was automatically populating values in a form that I created. My approach involved u ...

Getting the URL of a CSS background image in NodeJS and Express: A step-by-step guide

I've recently learned that using getComputedStyle in a Node environment is not possible due to it being a browser-specific behavior. Despite this, I am still interested in retrieving all background image URLs within Node and downloading them as shown ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...