Search code examples
angularexpressangular2-http

Angular 2 http.post sending empty object


Here's an authservice login, taken from here:

login(email: string, password: string): Observable<boolean> {
    return this.http.post(
        apiURL + '/admin/login',
        JSON.stringify({ email: email, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let token = response.json() && response.json().token;
            if (token) {
                // set token property
                this.token = token;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token }));

                // return true to indicate successful login
                return true;
            } else {
                // return false to indicate failed login
                return false;
            }
        });
}

In my component, I'm trying to subscribe like so:

login() {
    this.loading = true;
    console.log(this.model);
    this.authenticationService.login(this.model.email, this.model.password)
      .subscribe(result => {
        if(result === true) {
          this.router.navigate(['/']);
        } else {
          this.error = 'Username or password is incorrect';
          this.loading = false;
        }
      });
  }

I've done console logs along the line to determine if the data are actually being passed, and yes. Everything checks fine.

Except, the sent data is just { }

According to my Express console, that's the only thing coming through req.body. req.headers indicates the content types are proper, namely, Content-Type: application/json

I've tried sending same json request to API endpoint using POSTMan. Works fine.

Is there another trick up Angular 2's http.post sleeve?

What is wrong with the code above?


Solution

  • Posting answer here, might help someone. Thanks to @cartant for the pointers. I just had to look closer:

    • I didn't need to explicitly set the headers. by default, post sends Content-Type: application/json
    • I DID NOT have to stringify the data to send.

      login(email: string, password: string): Observable<boolean> {
      // this is optional
      // let headers = new Headers({ 'Content-Type': 'application/json' });
      // let options = new RequestOptions({ headers: headers });
      
      return this.http.post(
          apiURL + '/admin/login',
          { email: email, password: password },
          // options
          )
          .map((response: Response) => {
              // login successful if there's a jwt token in the response
              let token = response.json() && response.json().token;
              if (token) {
                  // set token property
                  this.token = token;
      
                  // store username and jwt token in local storage to keep user logged in between page refreshes
                  localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token }));
      
                  // return true to indicate successful login
                  return true;
              } else {
                  // return false to indicate failed login
                  return false;
              }
          });
      }