1

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)))
          }
        }
UI_Dev
  • 3,317
  • 16
  • 46
  • 92
  • This was happened on my past projects, to overcome this error use ` interceptor`. – AlokeT Mar 11 '19 at 06:08
  • Is 'content-type' (see the lowercase). Any way, if you're using HttpClient (not the old and deprecated http), by defect the data is sending in json format -you need'nt send httpHeader) – Eliseo Mar 11 '19 at 07:39
  • @Eliseo, cannot get you. can you elaborate? I'm using new httpclient which is in common/http – UI_Dev Mar 11 '19 at 07:42
  • use simple this.http.post(apiURL, data) or change your httpHeaders by const httpHeaders = new HttpHeaders ({ **'content-type'**: 'application/json' }); – Eliseo Mar 11 '19 at 07:46
  • 1
    Add CROS in your server side - i don't think the issue is on client - because the client pre-flight your request to http options but there is issue in your CROS try to fix it and try – Rahul Mar 11 '19 at 09:44
  • yes the issue is fixed from backend side – UI_Dev Mar 11 '19 at 09:56

1 Answers1

2

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)

Bhagwat Tupe
  • 1,905
  • 1
  • 13
  • 28