在Angular 5中发布形式urlencoded

Iri*_*ram 5 rest spring urlencode angular

我正在尝试使用Spring后端和Angular 5前端开发应用程序.对于登录我使用的是Spring Security,在前端我试图将登录数据发布为x-www-form-urlencoded.但是后端的用户名和密码都是null.Angular 5文档HttpClient仅提供了发布json数据的示例,并且Http已弃用.

任何有关如何解决这个问题的建议将不胜感激.

这是我的Angular代码:

constructor(public httpClient: HttpClient) {
    console.log('Hello RestService Provider');
}

login(username: string, password: string) {
    var body = 'username=' + username + '&password=' + password + "&remember-me=" +  false;
    var headers = new HttpHeaders();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    let options = {headers: headers, withCredentials: true};
    this.callPostWithOptions("login", body, options).then(data=>{
      this.getCurrentUser();
    });
}

callPostWithOptions(address, body, options) {
    return new Promise(resolve => {
      address = this._SERVER_HOST + ":" + this._SERVER_PORT + "/" + address;
      this.httpClient.post(address, body, options)
        .subscribe((data) => {
            resolve(data);
          },
          (err) => {
            console.log("error during POST", err)
          });
    });
}
Run Code Online (Sandbox Code Playgroud)

和服务器端点:

@RequestMapping(value = "/login", method = RequestMethod.GET)
@CrossOrigin(origins = "*")
public ModelAndView handle() {
    return new ModelAndView("/app/userOverview");
}
Run Code Online (Sandbox Code Playgroud)

编辑:我忘了提及,当我用Postman测试时,它没有问题

Bee*_*ice 2

HTTPClient模块仅适用于不可变类型。这意味着标头和参数无法修改。该append()操作实际上返回原始文件的副本,并添加了标头。

let headers = new HttpHeaders();
headers.append('...','...');// <- doesn't change the original object, but creates a new one!
Run Code Online (Sandbox Code Playgroud)

相反,您想要捕获返回的对象:

let headers = new HttpHeaders();
headers = headers.append('...','...');
Run Code Online (Sandbox Code Playgroud)

作为旁注,我将更改为callPostWithOptions使用toPromise()运算符

callPostWithOptions(address, body, options) {
   address = '...';
   return this.httpClient.post(address, body, options).toPromise();
}
Run Code Online (Sandbox Code Playgroud)