在Angular 5

时间:2017-11-16 15:45:20

标签: spring angular rest urlencode

我尝试使用Spring后端和Angular 5前端开发应用程序。对于登录我使用的是Spring Security,在前端我试图将登录数据发布为x-www-form-urlencoded。但是后端的用户名和密码都是null。 HttpClient的Angular 5文档仅提供了发布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)
          });
    });
}

服务器端点:

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

编辑:我忘了提及,当我使用Postman进行测试时,它可以正常运行

1 个答案:

答案 0 :(得分:1)

新的append()模块仅适用于不可变类型。这意味着无法修改标题和参数。 let headers = new HttpHeaders(); headers.append('...','...');// <- doesn't change the original object, but creates a new one! 操作实际上会返回原始文件的副本,并添加标题。

let headers = new HttpHeaders();
headers = headers.append('...','...');

相反,您希望捕获返回的对象:

callPostWithOptions

作为旁注,我会更改callPostWithOptions(address, body, options) { address = '...'; return this.httpClient.post(address, body, options).toPromise(); } 以使用toPromise() operator

Serial.println("Resistance 1: " + String(f1r) + " ohms");