Submission form-urlencoded in Angular 5

I am trying to develop an application using the Spring backend and the Angular 5 front end. For login I use Spring Security and in the front end I am trying to publish login data as x-www-form-urlencoded . However, the backend gets zero for the username and password. The Angular 5 documentation for HttpClient contains examples for publishing json data only, and Http has become deprecated.

Any suggestions on how to fix this would be greatly appreciated.

Here is my Angular code:

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

And the server endpoint:

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

Change I forgot to mention when I test it with Postman, it works without problems.

+5
source share
1 answer

The new HTTPClient module only works with immutable types. This means that headers and parameters cannot be changed. The append() operation actually returns a copy of your original with an added header.

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

Instead, you want to capture the returned object:

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

As a side element, I would change callPostWithOptions to use the toPromise() operator :

 callPostWithOptions(address, body, options) { address = '...'; return this.httpClient.post(address, body, options).toPromise(); } 
+1
source

Source: https://habr.com/ru/post/1273439/


All Articles