1

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?

13
  • Ok, is the data passed or not? A bit of a contradiction here. On one hand you say data is passed, on the other you say the data is just: { } :) Commented Jan 9, 2017 at 12:29
  • 1
    @AJT_82 sorry for the confusion. I mean, an empty object { } is the only thing the http.post sends. Commented Jan 9, 2017 at 12:30
  • what is this.model? Commented Jan 9, 2017 at 12:33
  • I would expect JSON.stringify({ email: email, password: password },) to be unhappy about the trailing comma; could you review and make sure this is a minimal reproducible example? Commented Jan 9, 2017 at 12:35
  • I'd be more inclined to follow this example Commented Jan 9, 2017 at 12:46

1 Answer 1

4

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;
            }
        });
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

So, what is the solution? What did you forget?
@Enrico "I DID NOT have to stringify the data to send."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.