6

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

Irina Avram
  • 1,492
  • 2
  • 20
  • 35
  • Can you show the server endpoint? – Héctor Nov 16 '17 at 15:49
  • I added it, but it's mainly handled by spring security – Irina Avram Nov 16 '17 at 15:52
  • 2 questions: (1) why are you adding the Access-Control-Allow-Origin header to the request? This is a [response header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) that should be sent from server to browser. (2) you call `callPostWithOptions` and provide as the 2nd argument `urlSearchParams`. Where does that come from? There are more problems with your code. For instance `headers.append()` returns a brand new object, but you think it is modifying the existing object – BeetleJuice Nov 16 '17 at 16:05
  • sorry, I tried a bunch of things and then edited the text to look like what I wanted in the first place before posting it here. now it should be fine. – Irina Avram Nov 16 '17 at 16:08
  • Possible duplicate of [HttpClient POST request using x-www-form-urlencoded](https://stackoverflow.com/questions/46714480/httpclient-post-request-using-x-www-form-urlencoded) – superjos Feb 16 '18 at 17:10

1 Answers1

2

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();
}
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165