-1

I am trying to submit a form in following way:

saveBuildcompany(): void {
    // @ts-ignore

  
    // @ts-ignore
    console.log(this.group?.value);
    
   let data2=this.group.value;
    let serializedForm = JSON.stringify(data2);

   console.log(data2);
   // data2.sociallinks.stringify;
    this.buildcompanyService.create(serializedForm)
      .subscribe({
        next: (res) => {
          console.log(res);
          this.submitted = true;
        },
        error: (e) => console.error(e)
      });
  }

The service is as follows:

create(data: any): Observable<any> {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

After all I get the exception like in a title. What I am doing wrong?

Bogdan Onyshenko
  • 415
  • 1
  • 6
  • 24

3 Answers3

1

Change "Content-Type" to application/x-www-form-urlencoded and "Accept" application/json if you are sending form data.

create(data: any): Observable<any> {
    let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'});
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }

or

create(data: any): Observable<any> {
    let headers = new HttpHeaders();
    headers.set('content-type', 'application/x-www-form-urlencoded')'
...
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }
  • Did not help. The exception is still the same. – Bogdan Onyshenko Jan 19 '22 at 19:40
  • 1
    Well I didn't comented on this yesturday, sorry. The problem was just in a way I was creating http headers variable. I was using append that found somewhere here in stack and that didn't actually changed the headers in a response. The code provided in the answer did just that. The actual api application supported only JSON. – Bogdan Onyshenko Jan 20 '22 at 05:14
0

You can Change "Content-Type" to application/x-www-form-urlencoded and "Accept" application/json. and try this below is the code snip.

create(data: any): Observable<any> {
    let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'});
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }
Pranav MS
  • 2,235
  • 2
  • 23
  • 50
0

And just to conclude all I sad above. The actual create function is look like this. This is sending correct header information:

create(data: any): Observable<any> {
    let headers = new HttpHeaders({'Content-Type': 'application/json', 'Accept': 'application/json'});
    return this.http.post(baseUrl+"/add", data, {headers: headers});
  }
Bogdan Onyshenko
  • 415
  • 1
  • 6
  • 24