HTTP post 将 null 附加到请求数据 ionic

HTTP post appends null to the request data ionic

我使用

从表单中获取这些数据

<form #form="ngForm" (ngSubmit)="myFunction(form.value)">

我将表单值发送到 HTTP post 方法

myFunction(formData){
   let headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
    });
    return new Promise( resolve => {
      this.http.post(this.my_api, formData, { headers: headers})
        .subscribe( data => {
          resolve(data);
        });
    });
}

当我安慰form.data时,我得到

{name: 'myname', address:'myaddress'}

但是 我在 api 中得到的是

{{"name":"myname", "address":"myaddress"} : null }

这让我很难在后端获取值。

P.S。我正在使用 Laravel 作为后端

为什么 : null 会附加到请求中? 如何获取 Laravel 后端中的值?

您必须对表单数据进行编码,然后将其发送到 API 调用

 getFormUrlEncoded(formData) {
        const formBody = [];
        for (const property in toConvert) {
            const encodedKey = encodeURIComponent(property);
            const encodedValue = encodeURIComponent(toConvert[property]);
            formBody.push(encodedKey + '=' + encodedValue);
        }
        return formBody.join('&');
    }

然后调用函数

this.http.post(this.my_api, this.getFormUrlEncoded(formData), { headers: headers})
        .subscribe( data => {
          resolve(data);
        });
    });