Search code examples
javascriptajaxangularform-data

When sending ajax POST FormData object key and value are not as set


I am programatically setting a FormData like so:

    const formData = new FormData();
    formData.append('id', '12345678');

After which I am sending a POST request with this object. (using angular HttpClient).

I am using Postman to debug the request and see what values were sent by importing the request as cURL and I see that the formData values appear differently.

key:------WebKitFormBoundaryI1mdsdmKkradYVMS\r\nContent-Disposition: form-data; name

value: "id"\r\n\r\n12345678\r\n------WebKitFormBoundaryI1mdsdmKkradYVMS--\r\n

What am I doing wrong?

I want to the send the data so that the server will receive an x-form-urlencoded request with the following object:

key: id
value: 12345678

EDIT: The solution is this:

 const body = new URLSearchParams({id: "12345678"});

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/x-www-form-urlencoded',
      })
    };
    return this.http.post(url, body.toString(), httpOptions).pipe(mergeMap( (response:any) => {
      console.log('response ', response);
      return of (response);
    }));

Thanks, Yaron


Solution

  • FormData objects generate multipart/form-data, not application/x-www-form-urlencoded by default.

    They are designed for handling file uploads for which there are no standard encoding method in application/x-www-form-urlencoded.

    Use a URLSearchParams object if you want to generate application/x-www-form-urlencoded data.

    const formData = new FormData();
    formData.append('id', '12345678');
    const query = new URLSearchParams(formData);
    console.log(query.toString());