json - 如何使用 Angular 响应式向期望常规 HTML 表单的服务器提交表单数据?
我正在用一个 Angular 响应式表单替换一个向旧 Perl 脚本发送数据的静态表单。我无法弄清楚如何格式化表单数据并使用 HttpClient.post 发送。很多我看到的通过这种方式发送数据的例子实际上是在请求中创建数据对象,而不是来自实际的表单,所以我很困惑
我尝试过只以表单形式发布数据,作为 JSON(我不确定服务器是否期待 JSON,它真的很老),在控制器中发送表单的数据对象
原始的静态表单 <form> 标签:
<form id="HTML_FORM" method="POST" role="form" action="https://sos.cnm.edu/MRcgi/MRProcessIncomingForms.pl" >
这只是使用普通的 HTML 提交输入提交的,这样做没有问题。
我的新模板:
<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>
控制器(零件)
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));
}
console.warn(this.opieForm.value); 会产生以下输出:
{TITLE: "test", First__bName: "test", Last__bName: "test", Email__bAddress: "[email ", dateNeeded: {…}, …}
返回的错误
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"
错误文本:
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.
...
当表单正确提交时,它会重定向到成功页面并发送一封电子邮件。