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

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

What causes the "v-col" width to suddenly alter after adding the "bg-red rounded" class?

I'm struggling to organize the data into blocks using Vuetify. When I apply the "bg-red rounded" class to the "v-col", it alters the width of the column, resulting in an undesired grid structure. Here is the template section of my Vue file. Some data ...

Number of Active Socket.IO Connections

I've been attempting to retrieve the connection count from the server socket, with the client application set up separately. Despite consulting various Stack Overflow articles that discuss different methods for obtaining socket connection counts, I ha ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Javascript and Codeigniter interaction: Using conditionals with Ajax

I am having trouble understanding this code snippet. I am currently studying Ajax and came across this piece of code that automatically inserts data. However, I am unsure about the line if(result=='12') then trigger ajax. What does the number 12 ...

The error message "TypeError: dom.getElementsByTagName is not a function in Node.js" indicates

I have just started learning HTML and web development. I am trying to extract a list of tags from an HTML document but I keep receiving the error message TypeError: dom.getElementsByTagName is not a function. I am making a GET request using axios, then u ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

The functionality of an HTML form utilizing JavaScript struggles to function correctly when integrated with PHP

I created a form with JavaScript that allows me to toggle between different fields based on the selection made with radio buttons. <?php require_once 'resources/menus/adminMenu.php'; ?> <div class="col-lg-offset-3 col-lg-6 "> < ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

The function res.send in Google Cloud is throwing an error

A scheduled Cron PubSub event triggers the function to retrieve data from an external API and update a Big Query table. During local testing (using the command npx @google-cloud/functions-framework --target pullElevate), the function operates as expected. ...

Updating table width using AngularJS/jQuery after completion of ajax request

One of my challenges involves a table that defaults to a specific width, such as 80% of its parent div. Initially, the table remains hidden using 'ng-if' until an ajax call is completed in this manner: This is reflected in the HTML code snippet ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Troubleshooting a visual problem using react-easy-crop within a React MUI Dialog

I'm having trouble adjusting the layout of MUI Dialog in combination with react-easy-crop. My goal is to achieve a perfect display of the dialog using react-easy-crop. However, the react-easy-crop component is covering the entire dialog. I attempted t ...

Challenges in verifying user identities and maintaining session continuity in passport.js/Node.js

Currently, I am in the process of setting up passport for authentication on my node.js web application. However, I am encountering some difficulties with properly storing session data. Right now, it seems like the session data is not being stored at all. ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

Produce HTML content onto Google Drive Documents using JavaScript

Currently, I am working on a project that requires me to render the HTML form output in a new Google Docs document (a Word file, not a spreadsheet). Despite my efforts to find information online, all I can come across is related to spreadsheets. The main ...

Utilize ES6 lodash to map the keys of an object fetched from an API

Currently, I am utilizing Vue 3 to send POST data to my API. The structure of the objects is as follows: const externalResults: ref(null) const resource = ref({ id: null, name: null, state: {} }) Prior to sending the data to the API, I am modifying ...

(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix? Find the most left & top connected '1' character Find the most right & bottom connected '1' character EDIT 2.0: To start, provide the coordina ...