Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it to storage. When I upload an image from localhost and make the fetch request, no file is found in the API route and I end up getting back an empty object. Strangely though, everything works fine when I send the request through Postman. I'm puzzled as to what could be causing this discrepancy and any help would be greatly appreciated!

Below is the code snippet that gets executed on the client side. It currently logs {} to the console.

 onClick={async () => {
      const data = new FormData();
      data.append("image", imageFile);
      const res = await fetch("/api/cropImages", {
        method: "POST",
        data,
      });
      console.log(await res.json());
    }}

Next, here's the relevant part of my API route:

import { IncomingForm } from "formidable";
export const config = {
  api: {
    bodyParser: false,
  },
};
export default async (req, res) => {
  const data = await new Promise((resolve, reject) => {
    const form = new IncomingForm();
    form.parse(req, (err, fields, files) => {
      if (err) return reject(err);
      resolve({ fields, files });
    });
  });
  const file = data?.files?.image;
  console.log(file);
  res.status(200).json({ file });
};

If you're curious, this is how the request looks like in Postman:

Postman request

And finally, here is the link to the image file: imagefile

Answer №1

Your issue may have stemmed from having an onClick function attached to your submit button within a form element without using preventDefault() in your method. Instead of incorporating logic into the onClick method, it may have been attempting to submit the form differently.

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

The value of Component.name is not consistent during the BUILD process in NextJS

I have multiple pages with different layouts. To switch between layouts, I am currently using the Component.name in _app.js. While this approach works during development, after building and starting the project with npm start, it seems like the Component.n ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...

Step-by-step guide to rapidly resolve all issues in VS Code using TypeScript

After extensive searching in VS code, I have not been able to find a quick fix all solution in the documentation or plugins. Is this feature actually non-existent, or is it possible that I am overlooking a keybinding? (I am currently utilizing typescript s ...

Tips for using rspec to test front end functionality?

In my Rails project, I have incorporated Vue.js using only the core library. Currently, most forms in the project are developed with Vue.js. When testing front-end features like form filling or validations using feature tests in RSpec, I found it to be qui ...

The presence of a Bootstrap addon is resulting in horizontal scrolling on mobile devices within the webpage

I am encountering a peculiar issue with an input-group in my cshtml file which features a Bootstrap addon. The problem arises on mobile devices, where upon focusing on the input field, the page scrolls horizontally to the right, revealing the right margin ...

Automatic playback of the next video in a video slider

Looking to upgrade my video slider functionality - switching between videos, playing automatically when one finishes. Struggling to find a solution that combines manual control with automatic playback. My attempt: function videoUrl(hmmmmmm){ ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...

Why isn't httpUploadProgress functioning correctly with Buffer data?

Recently, I have ventured into the world of node.js/express as I am attempting to create a multiple image uploading application utilizing cloudfront and an s3 bucket. My goal is to display a progress bar for the user by integrating socket.io for real-time ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...

Creating a table in HTML using the innerHTML property

document.getElementById("outputDiv").innerHTML = ""; document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>"; for(j=1;j<=10;j++) { document.getElementById("outputDiv").innerHTML += "<td align=center>"+St ...

What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object. How can I dynamically set the @click event in a v-for loop? I attempted to use this.m1, "this.m1", "m1", but encountered an error: fns.apply is not a function. Javascript: new Vue ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

Issue: Module 'curl' is not located at Function.Module._resolveFilename (module.js:489:15)

After installing node.js using the Windows installer, I noticed that the folder structure created was C:\Program Files\nodejs\node_modules\npm\node_modules. It seems like all the module folders are in the last node_modules director ...

Setting up Next.js to work with Ant Design and utilize both Less and Sass with CSS modules

Can anyone guide me on how to integrate Next.js with Sass and CSS modules while also incorporating Ant Design using Less styles for a smaller build size? I have been struggling to enable both CSS modules and the Less loader simultaneously. The examples p ...

Is it possible for URLSearchParams to retrieve parameters in a case-insensitive manner

Is it possible for URLSearchParams to search a parameter without being case-sensitive? For instance, if the query is ?someParam=paramValue, and I use URLSearchParams.get("someparam"), will it return paramValue? ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...