What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => {
  let bodyFormData = new FormData();
  for (let prop in params) {
    bodyFormData.append(prop, params[prop]);
  }
  return axios({
    method: "post",
    url: `${baseURL}/fetchCarouselData`,
    data: bodyFormData,
    headers: { "Content-Type": `multipart/form-data` },
  });
};

When making the API call using Axios in Next.js.

  1. If I use "Content-Type": multipart/form-data;, I encounter a 'content-type missing boundary' error.

  2. Using "Content-Type":

    multipart/form-data; boundary=${bodyFormData.getBoundary()};
    results in a bodyFormData.getBoundary is not a function error.

3) If I don't specify the content type at all ("header:{}") or omit the header parameter, I receive an "unsupported content-type" error.

How can this issue be resolved? Despite the errors, both methods still return a response from the API.

https://i.sstatic.net/OZiCr.png

https://i.sstatic.net/MLwxU.png

However, when testing in Postman, the result is obtained without any errors. https://i.sstatic.net/Borb7.png

Answer №1

Everything is functioning properly in v1.2.2:

import axios from 'axios';
import FormData from 'form-data';

console.log(axios.VERSION);

const data = {x: "foo", y: "bar"};

let bodyFormData = new FormData();
for (let key in data) {
  bodyFormData.append(key, data[key]);
}

const {data: {form, headers}} = await axios({
  method: "post",
  url: `http://httpbin.org/post`,
  data: bodyFormData,
  headers: {"Content-Type": `multipart/form-data;`},
});

console.log('headers:', headers);
console.log('form', form);

Alternatively, you can use a more concise method:

import axios from 'axios';

const data = {x: "foo", y: "bar"};

const {data: {form, headers}} = await axios({
  method: "post",
  url: `http://httpbin.org/post`,
  data: data,
  headers: {"Content-Type": `multipart/form-data`},
});

console.log('headers:', headers);
console.log('form', form);

Output:

1.2.2

headers: {
  Accept: 'application/json, text/plain, */*',
  'Accept-Encoding': 'gzip, compress, deflate, br',
  'Content-Length': '262',
  'Content-Type': 'multipart/form-data; boundary=--------------------------310666769872409476705056',
  Host: 'httpbin.org',
  'User-Agent': 'axios/1.2.2'
}
form { x: 'foo', y: 'bar' }

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

Creating a hover effect for displaying image masks

My website features a profile page displaying the user's photo. I am attempting to create a functionality where when the user hovers over their photo, a transparent mask with text appears allowing them to update their profile picture via a modal. How ...

Calculate the difference in days between two selected dates from an Ajax Datetime Picker using JavaScript

How can I use JavaScript to count the number of days between two selected dates from Ajax date time pickers in my aspx page? The script should automatically input this calculated value into a designated "Number_Of_Days" text box without requiring a page ...

Tips for passing dynamic latitude and longitude values to a JavaScript function within an AngularJS framework

I am facing an issue with displaying a dynamic marker on Google Maps. I can show a static lat long marker, but I am struggling to pass dynamic lat long values to the function. How can I pass {{names.lat}}, {{names.longitude}} to the function so that I can ...

The functioning of invoking JavaScript confirm from the code behind is experiencing issues

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click Dim ResourceObject As Object Dim js As [String] = (vbCr & vbLf & " if(confirm('Are you sure you want to delete from th ...

Can one transition from using a callback to a returning Promise in order to implement an ErrorFirstCallback strategy?

In Node.js documentation, it is explained that an ErrorFirstCallback is triggered when the referred function fails. Error-first-callbacks in Node.js I have been practicing with this callback pattern and I am curious to know if it is possible to refactor i ...

How to use JavaScript regular expressions to verify that an input contains more than zero characters

Can someone help me with a simple regex issue? I've tried searching online but couldn't find a suitable example. I'm struggling with regex and just need to ensure that an input contains more than 1 character (i.e. is not blank). My code uses ...

Encountering a "Module not found" error while attempting to access user session in getServerSideProps. The specific error is: "Error: Can't resolve 'dns'"

Currently, I am utilizing the next-auth module in my project. By integrating the mongodb adapter, users are automatically created in the database with basic information such as name, email, and avatar. However, I require additional data to be added on top ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...

Building a listview using Angular, MySQL, and Node.js

As a newcomer to Angular, I've been navigating my way through the learning process with some success but also encountering challenges. Although I've managed to resolve certain issues within the application, such as successfully inserting data int ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

Correct Way to Use 'useState' in Formik's 'onSubmit' Function?

I recently encountered an issue while using Formik in my Next.js application. Specifically, I am facing a problem with the submit `Button` component, which accepts a `showSpinner` prop to control its behavior. When set to true, the button is disabled and d ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

I am encountering an issue with the Link tag from next/link that is throwing an error. The error message states: "React.Children.only expected to receive a single React element

Hey everyone, I've come across an issue with using next/link in my code. Every time I replace the anchor tag with the "Link" tag, I encounter an error. I've searched for a solution but haven't found one yet. Any help would be greatly appreci ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

Leveraging AJAX, PHP, and MySQL for showcasing tabular information

My goal is to dynamically display a column of data labeled as [pin], depending on the values of [plan] and [order_id]. Specifically, when plan=9 and order_id=0. I am looking to achieve this without having to reload the entire page by utilizing Ajax. Below ...

Body-Processing Protocol

When I send a cURL POST request, it looks like this: curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }' Within my NodeJS application, the request passes through the bodyParser.json() middl ...

A guide on transforming a JSON object representing an HTML element into a live HTML element for display on a webpage using C#, JavaScript, or jQuery

I am looking to retrieve a JSON object from a database and convert it into HTML format. Here is an example of the JSON structure: {"input":{ "name":"fname", "type":"text", "placeholder":"Ente ...

Semantic-release failing to generate a new version update for package

I'm in the process of setting up semantic release for my NPM package to automate deployment with version updates. However, after migrating from an old repo/npm package to a new one, I'm facing issues with semantic versioning not creating a new re ...