skip to Main Content

I’m attempting to send a multipart/form-data request from a react application to a backend api. When the request is submitted the Content-Type is application/x-www-form-urlencoded.

enter image description here

I tried a few different things including switching from put to putForm. Which, does change the content-type to multipart/form-data, but doesn’t include the boundary which causes the api to reject it.

import axios from "axios";
import getEnvironment from "../constants/environments";

export const register = async (request: FormData) => {
    return axios.put(`${getEnvironment.BaseUri}/email/register`, request);
}

2

Answers


  1. Chosen as BEST ANSWER

    The resolution was that the axios version 1.1.3 had a bug. I upgraded to 1.4.0

    Thank you @Phil for pointing it out!


  2. The problem is that you are using the put method instead of the putForm method. The put method only supports sending application/x-www-form-urlencoded data, while the putForm method supports sending multipart/form-data data.

    To fix this, you need to change your code to use the putForm method. Here is the updated code:

    import axios from "axios";
    import getEnvironment from "../constants/environments";
    
    export const register = async (request: FormData) => {
        return axios.putForm(`${getEnvironment.BaseUri}/email/register`, request);
    }
    

    This will now send the request with the correct Content-Type and boundary, and the API should be able to accept it.

    Here is a breakdown of what is happening in the code:

    • The axios.putForm method takes two arguments: the URL of the API
      endpoint and the FormData object.
    • The FormData object is used to store the data that will be sent to the API.
    • The Content-Type header is automatically set to multipart/form-data when the putForm method
      is used.
    • The boundary is automatically generated and added to the
      Content-Type header.

    I hope this helps! Let me know if you have any other questions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search