Roomey
Roomey

Reputation: 716

Unsupported Media Type 415, but in Postman works fine

After registration user get a link, which consist of userId and token. When user click on it - angular project opens, then angular takes userId and token from link, and send a post method to backend for verifying email.

Link example

http://localhost:4200/user/confirmemail/?userId=9bc9a474-d10c-438b-8953-1c32fc57551b&token=Q2ZESjhPRkF6d3BPQ1E5TmtLbWplTnlIZ3g3bzJEVEZQZDQ3MFNSblExaWxBTWh3MmdSMWl2ZkU3djZxcWR3bmY4OFMwd2l6STZOY3VMR2FoZ1ZCM28rWFo1YlJhejhOTE5pamFFdGRETTNiNGttT0lOQ2dZVmdLRVlRdWlKRmtQMVpEWHE0b2t2NVBQZTZ0bkR3cUdrb3JiMWRIQUpRUE5pMTZjTW96YUdJcVZBUUxPSG5pd3NDU3BDeTBNREMvMTVyTlhUNUpCL2tRZTJWMjJlTzVHZ1dDbEh5VWNESGNsNlVTQkpXZ1FJaThDTk1kcUovcmdtV0ZEdEQza2hXR1p6V0pEdz09

Post method, which verify email:

        [HttpPost("confirmEmail/{userId}")]
        public async Task<IActionResult> ConfirmEmail(string userId, [FromBody]string token)
        {
            var codeDecodedBytes = WebEncoders.Base64UrlDecode(token);
            var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ConfirmEmailAsync(user, codeDecoded);
            return Ok(result);
        }

It works fine in postman: enter image description here

Error in Angular project: enter image description here

Getting userId and token in Angular

  userId: string;
  token: string;
  constructor(private activatedRoute: ActivatedRoute, private authService: AuthService) {
    this.activatedRoute.queryParams.subscribe(params => {
          this.userId = params['userId'];
          this.token = params['token'];
      });
  }

  ngOnInit(): void {
    this.confirmEmail();
  }

  confirmEmail(){
    this.authService.confirmEmail(this.userId, this.token).subscribe(data => { console.log("success")});
  }

(AuthService) Sending data to backend

  confirmEmail(userId: string, token: string){
    console.log(userId);
    console.log(token);
    return this.http.post(this.authUrl + `confirmemail/${userId}`, token);
  }

Upvotes: 1

Views: 476

Answers (1)

StepUp
StepUp

Reputation: 38199

Try to set Content-Type to json type:

confirmEmail(userId: string, token: string) {
    const body = JSON.stringify(token);
    const options = {
      headers: new HttpHeaders().append('Content-Type', 'application/json')
    };

    return this.http.post(this.authUrl + `confirmemail/${userId}`, body, options)
          .pipe(
              map(res => res)
            , catchError(this.handleError())
          );
}

Upvotes: 2

Related Questions