415 (Unsupported Media Type) - POST REST API - Angular 11

Viewed 59

I want to send data from angular reactive forms into REST, i wrote method like this

export class ContactComponent implements OnInit {
  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder, private contactService: ContactService, private router: Router) {
  }

  ngOnInit(): void {
    this.form = this.fb.group(
      {
        firstName: ['', Validators.required],
        lastName: ['',
          [
            Validators.required,
            // Validators.minLength(6),
            Validators.maxLength(30)
          ]
        ],
        email: ['',
          [
            Validators.required,
            Validators.email
          ]
        ],
        phone: ['',
          [
            Validators.required,
            Validators.minLength(8),
            Validators.maxLength(10)
          ]
        ],
        message: ['', Validators.required]
      },
    );
  }

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  onSubmit(): void {
    this.submitted = true;
    if (this.form.invalid) {
      return;
    }
    const contactFormDto: ContactFormDto = {
      firstName: this.form.get('firstName').value,
      lastName: this.form.get('lastName').value,
      email: this.form.get('email').value,
      phone: this.form.get('phone').value,
      message: this.form.get('message').value
    };
    this.contactService.addFormContact(contactFormDto)
    .subscribe({
      next: (response) => {
        console.log(response);
        this.router.navigate(['/contacts']);
      },
      error: (error) => console.log(error),
    });
    this.onReset();
  }

  onReset(): void {
    this.submitted = false;
    this.form.reset();
  }
}

and my contactService

const apiUrl = `${environment.apiUrl}contacts`;
const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json',
  })
};

@Injectable({
  providedIn: 'root'
})
export class ContactService {

  constructor(private httpClient: HttpClient) {
  }

  addFormContact(contactForm: ContactFormDto): Observable<ContactFormDto> {
    return this.httpClient.post<ContactFormDto>(apiUrl, contactForm, httpOptions);
  }
}

Before that I used ngModel and create an object that reflected the data I send.

Rest API :

@RestController
@RequestMapping("/contact")

public class ContactController {
    private final ContactService contactService;

    public ContactController(ContactService contactService) {
        this.contactService = contactService;
    }

    @PostMapping
    public ResponseEntity add(@RequestBody ContactFormDto contactFormDTO){
        contactService.add(contactFormDTO);
        return new ResponseEntity(HttpStatus.CREATED);
    }
}

My question is, why I get 415 Unsupported media in console? Angular in version 11

image1 console

second image image2 console

0 Answers
Related