I'm trying to develop an application using a Spring backend and an Angular 5 frontend. For the login I am using Spring Security and in the frontend I am trying to post the login data as x-www-form-urlencoded
. However the backend receives null for both username and password. The Angular 5 documentation for HttpClient
provides examples only for posting json data and Http
became 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");
}
Edit: I forgot to mention, when I test it with Postman it works without a problem
The new HTTPClient
module only works with immutable types. This means that headers and params cannot be modified. The append()
operation actually returns a copy of your original, with the 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 sidenote, I would change callPostWithOptions
to use the toPromise()
operator:
callPostWithOptions(address, body, options) {
address = '...';
return this.httpClient.post(address, body, options).toPromise();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With