Update the HTML form action to use the Fetch API to communicate with the webserver

I successfully managed to store files on my computer by utilizing the HTML form action attribute and then processing this request on my Express webserver.
However, when I attempted to switch to using an event listener on the submit button of the form instead of relying on the action attribute to send the post request, I encountered difficulties in making it work.

Specifically, I encountered a 400 bad request error message.

Fetch

let form = document.querySelector('#uploadForm')
let inpFile = document.querySelector('#inpFile')
form.addEventListener('submit', async event => {
    event.preventDefault()
    const formData = new FormData()
    formData.append('inpFile', inpFile.files[0])
    fetch('http://myip/upload', {
        method: 'POST',
        headers: {
            'Content-Type' : 'multipart/form-data'
        },
        body: formData
    }).catch(console.error)
})

HTML

<form ref='uploadForm' 
  id='uploadForm' 
  method='post' 
  encType="multipart/form-data">
    <input type="file" name="sampleFile" id="inpFile" />
    <input type='submit' value='Submit' />
</form>     

Express Server

const express = require('express')
const app = express();
const path = require('path')
const things = require('./routes/things')
const fileUpload = require('express-fileupload')

app.post('/upload', (req, res) => {
    let sampleFile = req.files.sampleFile
    sampleFile.mv(__dirname + '\\files\\' + sampleFile.name, (err) => {
        if (err)
            return res.status(500).send(err)
        res.send('File uploaded!')
    })
})

Answer №1

If you want to make your Express code work correctly with your HTML and fetch code, it should be structured like this:

const express = require('express')
const app = express();
const path = require('path')
const things = require('./routes/things')
const fileUpload = require('express-fileupload')

app.use('/upload', fileUpload({
  createParentPath: true
}));

app.post('/upload', (req, res) => {
    const { inpFile } = req.files;

    inpFile.mv(path.join(__dirname, 'files', inpFile.name))
      .then(() => res.send('File uploaded!'))
      .catch(err => res.status(500).send(err));
})

In order for everything to function properly, you must bind middleware to the application like so:

app.use('/upload', fileUpload({
  createParentPath: true
}));

Furthermore, ensure that your file object is located in req.files.inpFile.

Lastly, headers must be removed from your fetch request.

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

Use JavaScript or jQuery to implement the position absolute styling

I am currently working on a website where the navigation is aligned to the right side. However, I am facing an issue where the last menu item dropdown extends beyond the page because it is absolutely positioned to the left of its parent element. I am act ...

Using the parent id in knockoutJs to create a nested menu

I'm currently attempting to create a nested menu using the JSON data provided by the client. Here is the data: var serverData = [ { Id: "menuColorSearch", Text: "Color search" }, { Id: "menuAncillaryProductM ...

Is there an alternative method to retrieve the client's user agent if getStaticProps and getServerSideProps cannot be used together?

I am currently facing a challenge with the website I'm working on as it lacks a responsive design. This means that the view I display is dependent on the user agent of the client. In order to achieve this, I have been using getServerSideProps to deter ...

Using a set formatter in jqGrid within a personalized formatter

Can I incorporate a predefined formatter into a custom formatter? Here is an example using the colModel: colModel: [ ... { name: 'col1', formatter: myFormatter } ... ] Below is the custom formatter function: function myFormatter(cellVal ...

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

The AngularJS function invoked itself within the structure

When working with my form, I encountered a problem involving custom input directives and text fields. In addition to these elements, there are buttons: one for adding a new input to the form which is linked to the function $scope.AddNewItem() in the contro ...

What could be causing my Bootstrap carousel to only slide once?

I'm currently working on integrating a Bootstrap Carousel into my website, but I've encountered an issue where it moves only once and then becomes unresponsive. After checking the file order, I couldn't find any issues there. So, I'm qu ...

Save a newly uploaded image to Github utilizing NodeJS and the Github API

Struggling to upload an image to my Github repo using NodeJS and Github API has been a challenge for me. I have managed to create the SHA, Commit Tree, and all necessary steps, but the final hurdle is passing the image to the API and saving it as an actual ...

What are the steps to applying strike-through text in Vue.js?

I am currently working on a to-do application using Vue.js and I want to implement a feature where the text rendered in HTML has a line through it when the user checks an item off the list. Here is the snippet of my code: <html> <head> & ...

Guide on validating an Australian phone number with the HTML pattern

When it comes to PHP, I have found it quite simple to validate Australian phone numbers from input using PHP Regex. Here is the regex pattern I am currently using: /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ | ...

Halt the countdown of a Jquery or Javascript timer

Searching for a straightforward solution to stopping a JavaScript/jQuery timer function has proven to be more challenging than I expected. The function in question initiates a timer, as shown below: function startTimer() { (function ($) { //timer for ...

Mastering the Art of Integrating API and JSON!

I've developed a bot using botkit and the Zendesk API to retrieve information. There's a function in my bot that prompts the user for a search term, searches for relevant information using the Zendesk API, and displays the result. I'm faci ...

Compare several objects or arrays based on a selected array and combine them into a single object containing all matching elements from the selected array

selection = ["A", "lv3", "large"] Data = [{ id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " medium", }, id:2, title:"this is test 1", category:"C ...

Is it possible to retrieve the value of a particular field from a table?

My goal is to create a table that displays data about various users awaiting admin approval. Each row represents a specific user, and when the approve button on a particular row is clicked, I want to open a new window displaying detailed user information f ...

Can you explain how differential inheritance works in JavaScript?

This response to a question about the Object.create() method in JavaScript on SO discusses the concept of differential inheritance. The explanation given is as follows: This particular technique enables you to easily establish differential inheritance, ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error. Here is my file structure: app components Product.js pages Products [id].js layou ...

Uncover the underlying reasoning within the Vuex state

Struggling to find the right way to structure my Vuex store for a particular issue. In my store, I have an array of buttons or actions, totaling in the hundreds. Here's how they are currently organized: buttons: [ { text: 'Button 1', ...

Issue with AngularJS: Data not being displayed in table after xmlhttp request

Greetings to all! I am a novice in the realm of angular js, and I have concocted the ensuing page designed to exhibit a table of employee details sourced from " http://localhost:8080/SpringRestHibernateWebTest/employee/listEmployee " as a json object. < ...

jQuery is not active on responsive designs

I have implemented a script in my JavaScript code that changes the color of the navigation bar when scrolling. The navigation bar transitions to a white color as you scroll down. However, I am facing an issue with responsiveness and would like to deactivat ...