I'm replacing a static form that sends data to an old perl script with an angular reactive form. I can't figure out how to format the form data and send it using HttpClient.post
. A lot of examples I'm seeing for posting this way actually create the data object in the request itself, not coming from an actual form, so I'm stumped
I've tried posting the data as just the form, as JSON (I'm not sure the server is expecting JSON, it's really old), sending the form's data object in the controller
the original static form <form>
tag:
<form id="HTML_FORM" method="POST" role="form" action="https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl" >
This was just submitted using a regular HTML submit input, and that works fine.
My new template:
<form [formGroup]="opieForm" (ngSubmit)="onSubmit()">
<input type="text" class="form-control" id="TITLE" formControlName="TITLE" #TITLE placeholder="required" >
...
<button class="btn btn-primary" [disabled]="!opieForm.valid" type="submit">Submit form</button>
</form>
The controller (parts)
opieForm: FormGroup;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})};
this.opieForm = this.fb.group({
TITLE: [ '', Validators.required ],
// lots of other inputs
})
onSubmit = () => {
console.warn(this.opieForm.value);
return this.http.post('https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl', this.opieForm.value, this.httpOptions)
.subscribe(res => console.log(res), error => console.error(error));
}
The console.warn(this.opieForm.value);
produces output:
{TITLE: "test", First__bName: "test", Last__bName: "test", Email__bAddress: "test@test.com", dateNeeded: {…}, …}
The error that's returned
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl", ok: false, …}
error: {error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "<!DOCTYPE>↵ <HTML>↵ <!-- FP VERSION: 11.6.04 -->↵↵…ipt language = "javascript">self.close()</script>"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl"
Error text:
SyntaxError: Unexpected token < in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:7639:51)↵ at ZoneDelegate.push.
...
When the form submits correctly it redirects to a success page and sends an email.