使用httpClient的POST请求正文的语法错误

时间:2019-03-04 18:17:39

标签: angular typescript request httpclient

我正在尝试使用正文编写POST请求。 除了我要求的内容外,一切都正常。 我的服务器收到...:

body: { '{"email":"test@test.com","password":"a"}': '' },

那不是我想要的...我想要这样的东西:

body: {"email":"test@test.com","password":"a"},

我不明白自己做错了什么...这是我的代码。

post(url: string, object: any, httpOptions?: {}) {
    return this.http.post<Response>(this.baseUrl + url, object, httpOptions);
}

我在这里使用此功能:

  let user = new User();
  user.email = this.loginForm.get('email').value;
  user.password = this.loginForm.get('password').value;
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded'
    })
  };
  this.httpService.post('api/authenticate', user, httpOptions).subscribe(result => {
    alert(result.message);
  });

最后,我的用户类别。

export class User {
    pk_user: number;
    email: string;
    password: string;
    username: string;
    society: string;
    firstname: string;
    lastname: string;
    locality: string;
    npa: number;
    address: string;
    available: number;
    created_at: string;
    updated_at: string;
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

最后,我找到了这个解决方案:

post(url: string, object: any, httpOptions?: {}) {
    let httpParams = new HttpParams();
    Object.keys(object).forEach(function (key) {
        httpParams = httpParams.append(key, object[key]);
    });
    return this.http.post<Response>(this.baseUrl + url, httpParams, httpOptions);
}