user3049904
user3049904

Reputation: 70

Angular 8: URL encoded form POST

I want to post form data to a server that accepts and returns text/html/xml. I am effectively trying to emulate a normal URL encoded form POST. My Angular 8 POST function successfully posts (200 OK), but the server can't understand the data because it is JSON and not URL encoded.

Response and request headers state Content-Type: text/html; Charset=utf-8 and Accept: text/html, application/xhtml+xml, */* and I have added responseType: "text" to the httpClient options. Why is the server still being sent JSON and not URL encoded data?

// obj2 = output from ngForm
// baseUrl2 = server that sends and receives text/html/xml

public postForm(obj2) {
    return this.httpClient
    .post(this.baseUrl2, obj2, {
        headers: new HttpHeaders({
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "text/html, application/xhtml+xml, */*"
        }),
        responseType: "text"
    })
    .map(data => data);
}

Form data sent:

{"Form data":{"{\"personsNameText\":\"name9\",\"centreEmailAddressText\":\"[email protected]\",\"centreTelephoneNumberText\":123456789,\"centreNumberText\":\"ab123\",\"centreNameText\":\"ab123\",\"invoiceText\":\"123456789\",\"currencyText\":\"GBP\",\"amountText\":\"100\",\"cardtypeText\":\"Credit card\",\"commentsText\":\"Comments.\",\"declarationText\":true}":""}}

What I want:

[email protected]?centreTelephoneNumberText=123456789?centreNumberText=ab123?centreNameText=ab123?invoiceText=123456789?currencyText=GBP?amountText=100?cardtypeText=Credit card?commentsText=Comments.?declarationText=true

Upvotes: 1

Views: 1946

Answers (2)

user3049904
user3049904

Reputation: 70

So, this solution solved various problems for me:

  1. Posting x-www-form-urlencoded data using Angular 8's forms and HttpClient
  2. Correcting unwanted encoded characters
    • My specific problem was that a unique verification string contained ampersands that were being converted to HTML entities, i.e. & to &.
// userdata.service.ts

public postForm(obj) {
  return this.httpClient
    .post(this.baseUrl2, obj, {
      headers: new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Referer": "http://referer.com" // Replace with your own.
      }),
      responseType: "text"
    })
    .map(data => data)
    .pipe(
      retry(1),
      catchError(this.handleError)
    );
}

// app.component.ts

PostForm(userdata) {
    // Stringify and convert HTML entity ampersands back to normal ampersands.
    const corrected = JSON.stringify(userdata).replace(/(&)/gm, '&');
    // Convert back to JSON object.
    const corrected2 = JSON.parse(corrected);
    // entries() iterates form key:value pairs, URLSearchParams() is for query strings
    const URLparams = new URLSearchParams(Object.entries(corrected2));
    // Convert to string to post.
    const final = URLparams.toString();
    // Post it
    this.userdataService.postForm(final).subscribe(reponse2 => {
        console.log(reponse2);
    });
}

URLSearchParams() was the breakthrough and, as Vlad suggested, being absolutely sure of the type one is dealing with. I should have used Types to avoid confusion. I probably should use Angular Interceptors to deal with the character manipulation.

Upvotes: 0

Vlad Vidac
Vlad Vidac

Reputation: 998

I'm not sure of the type of the obj2 object here but I'll assume it's somethings like

interface UserFormData {
  ['Form data']: { [name: string]: value };
}

You would need to transform this to FormData before posting it. Something along the lines:

const formEncodedObj2 = new FormData();
const obj2Keys = obj2['Form data'];
Object.keys(obj2Keys).forEach(key => formEncodedObj2.append(key, obj2Keys[key]));

And then send the formEncodedObj2 object.

Upvotes: 2

Related Questions