Submitting an HTTP POST REQUEST with both an image and text

Is there a way to send an image with text from VueJs to an ExpressJs backend?

I've currently implemented two HTTP POST requests for this process.

Please note: "this.albumName" and "this.albumDesc" contain text, while the formData variable holds the image data.

createAlbum() {
      const formData = new FormData();
      for (let file of Array.from(this.myAlbumImages)) {
        formData.append("files", file);
      }

      if (this.albumName) {
        axios
          .post("http://localhost:9001/image/album", {
            ALBUM: this.albumName,
            DESCRIPTION: this.albumDesc
          })
          .then(resp => console.log(resp))
          .catch(err => console.log(err));
        setTimeout(function() {
          axios
            .post("http://localhost:9001/image/album", formData)
            .then(resp => console.log(resp))
            .catch(err => console.log(err));
        }, 3000);

        this.albumName = "";
        this.albumDesc = "";
      } else {
        alert("Please fill out the form above.");
      }
    },

Here is the corresponding Backend code snippet.

This code segment creates a folder based on the provided data and includes a folder named undefined.

router.post('/album', (req, res) => {
let sql = "INSERT INTO GALLERY SET ALBUM = ?, DESCRIPTION = ?";
let body = [req.body.ALBUM, req.body.DESCRIPTION]
myDB.query(sql, body, (error, results) => {
    if (error) {
        console.log(error);
    } else {
        let directory = `C:/Users/user/Desktop/project/adminbackend/public/${req.body.ALBUM}`;
        fse.mkdirp(directory, err => {
            if (err) {
                console.log(err);
            } else {
                console.log(directory);
            }
        })
    }
})

I suspect that NodeJS being Asynchronous might be causing the creation of the undefined folder.

Answer №1

The reason for the behavior you are experiencing is due to sending two separate requests to the same route. The first request includes ALBUM and DESCRIPTION form field values, but not the files. The second request (inside a setTimeout function) will only contain the files without any other fields, causing references like req.body.ALBUM to return undefined.

To resolve this issue, you can send all data (text fields and files) in one request by following this approach:

const formData = new FormData();
for (let file of Array.from(this.myAlbumImages)) {
  formData.append("files", file);
}
formData.append("ALBUM", this.albumName);
formData.append("DESCRIPTION", this.albumDesc);
axios.post("http://localhost:9001/image/album", formData)
     .then(resp => console.log(resp))
     .catch(err => console.log(err));

FormData always uses the content type multipart/form-data. In order to parse it on the server side, you will need an Express middleware that parses multipart forms and provides access to both fields and images. One example of such middleware is multer.

Answer №2

If you're struggling with uploading images using fetch, check out this helpful link: How to post image with fetch?

const fileInput = document.querySelector('#your-file-input') ;
const formData = new FormData();

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

    const options = {
      method: 'POST',
      body: formData,
      // If you add this, upload won't work
      // headers: {
      //   'Content-Type': 'multipart/form-data',
      // }
    };

    fetch('your-upload-url', options);

When it comes to sending image files as API response in Node Express server, you can find guidance in this link: Node Express sending image files as API response

app.get('/report/:chart_id/:user_id', function (req, res) {
    res.sendFile(filepath);
});

For more information and official documentation on this topic, visit: http://expressjs.com/en/api.html#res.sendFile

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

Having trouble incorporating a JavaScript snippet from Google Trends into an HTML webpage

Hey everyone, I've been trying to incorporate a JavaScript script to display Google Trends on an HTML page. I copied the embed code directly from the first image at and modified it as follows. Unfortunately, it's not working as expected. <ht ...

Using ReactJS to pass an onClick event to a different component

Is there a way to implement the onClick event on an anchor tag to update state in another component? Utilizing onClick in Card.js Component import React from 'react' import PropertyLightbox from '../global/PropertyLightbox' const Car ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

Client-Side Isomorphic JS: A Guide to Using HTTP Requests

Seeking advice on data population for isomorphic flux apps. (Using react, alt, iso, and node but principles are transferable) In my flux 'store' (), I need to fetch data from an api: getState() { return { data : makeHttpRequest(url) ...

How can I clear all jQuery toggled classes that have been added across the entire webpage in an Angular project?

Upon clicking a link within an element, the following CSS is applied: <a class="vehicleinfo avai-vehicle-info-anc-tag" ng-click="vehicleInfo($event)">Vehicle Info <span class="s-icon red-down-arrow"> </span> </a> $scope.vehic ...

Connecting Node.js with Express.js allows you to access the session data from the "upgrade" event

I'm currently facing a challenge with accessing the session object from an 'upgrade' event triggered by my Node.js server using the Express.js framework. Although I have successfully set up Session support and can retrieve it from the standa ...

Displaying the unique values based on the key attribute

I'm developing a category filter and struggling to showcase the duplicate options. Within my array of objects: filterData = [ { name: 'Aang', bender: 'yes', nation: 'Air', person: 'yes', show: 'ATLA&apo ...

Socket.emit allows for the transmission of various data points

Can someone help me with an issue I'm facing regarding socket.emit inside socket.on concatenating the same value after every emitting? Below is the code snippet on the server-side: io.on('connection', function(socket){ let balance = 6000; ...

Guide to implementing client-side validation in MVC 4 without relying on the model

Currently, I am developing an ASP.NET MVC 4 project where I have decided not to utilize View Models. Instead, I am opting to work with the classes generated from the Entities for my Models. I am curious if there are alternative methods to achieve this. A ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extend ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

Utilize jQueryUI sortable to serialize a list item within an unordered list

I'm looking to learn how to generate a JSON or serialize from a ul element with nested list items. Here's an example: <ul class="menu send ui-sortable"> <li id="pageid_1" class="ui-sortable-handle">Inscription <ul class="menu ...

Issue encountered with the DevExtreme npm module: Uncaught TypeError - $(...).dxButton is not recognized as a function

Instructions for installing DevExtreme npm can be found on their official page here: https://www.npmjs.com/package/devextreme var $ = require('jquery'); require('devextreme/ui/button'); var dialog = require('devextreme/ui/dialog&a ...

Tips for switching out images depending on the time of day

Currently, I have a script that dynamically changes the background color of my webpage based on the time of day. However, I am facing issues trying to implement a similar functionality for replacing an image source. The current code is also time zone-based ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...

Displaying items as objects in search results in Kendo Angular's auto complete feature

Seeking assistance with implementing Kendo Angular's auto complete widget using server filtering. Following the service call, the popup displays [object Object] and the count of these matches the results retrieved from the server. Could someone kindly ...

Static response is the way to go! Asynchronous responses just don't cut it

Currently in the process of developing an angular directive for displaying real-time charts. Below is the code snippet that encompasses everything, including link: function() { }, within the directive. Here's the code for a static directive that func ...

An error was encountered: SyntaxError - An unexpected token '!' was found

I am having trouble creating a react cluster map. I encountered a SyntaxError, and I'm not sure what went wrong. Initially, my map was working fine, but after using the use-supercluster npm package, it started showing an Uncaught SyntaxError: Unexpect ...

Execute a GET request within a route from a different route

I have multiple routes and I need to retrieve data from the user's route (GET method) by calling it within the GET method of the group's route. What is the most efficient way to accomplish this? Here is a snippet of my app.js: var express = requ ...