【问题标题】:Body of POST Request with httpClient got bad syntax使用 httpClient 的 POST 请求正文语法错误
【发布时间】:2019-03-04 18:17:38
【问题描述】:

我正在尝试使用正文编写 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;
}

感谢您的帮助

【问题讨论】:

  • 变量object是什么?这是一个 JSON 对象吗?
  • 我在上面编辑我的帖子
  • 完全去掉httpOptions后格式化好吗?
  • 你可以在你的 post 方法中使用 console.log 对象吗?确保它看起来像你想要的。另一件事值得尝试,而不是执行 new User() 并分配字段,您应该能够只执行 let user = this.loginForm.value;那只会给你你想要的json
  • 我收到了Object { email: "test@test.com", password: "a" },好的,谢谢您的建议

标签: angular typescript request httpclient


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-04-11
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多