UI_Dev
UI_Dev

Reputation: 3427

angular 7 not sending header on request

I'm trying to send content-type headers for the below post request to allow json request, but it throws me an error Invalid CORS request with OPTIONS request method. It doesn't even send POST method.

Here, I cannot able to use RequestOptions which is depreciated.

PS: This is working fine when I send the request with postman. And, Backend code is handled with CORS request already.

From Backend java code, this the error I'm getting

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Where am I missing?

 postSubmit(){

        let data = { "name":"John", "age":30 };

         const httpHeaders = new HttpHeaders ({
            'Content-Type': 'application/json'
          });

            return this.http.post<any>(apiURL, data, {headers : httpHeaders})
            .pipe(catchError(error => this.handleError(error)))
          }
        }

Upvotes: 1

Views: 1774

Answers (1)

Bhagwat Tupe
Bhagwat Tupe

Reputation: 1943

To define the content-type with the new HttpHeaders class you need to

  1. Just Import import { HttpHeaders } from '@angular/common/http';
  2. Create httpOptions object that will be passed to every HttpClient save method

    import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) };

  3. Call the API this.http.post<Datatype>(API url, Bady Parameter, httpOptions)

Upvotes: 2

Related Questions