2

I'm not sure what the deal is, hopefully someone can give me some help!

I'm trying to make a POST to the backend API, but I get a 415 status code because the content-type is being sent as "text/plain" but this endpoint is expecting application/json. I thought maybe it was the API, but the POST works just fine in PostMan (see screenshot below).

I've tried to manually set the content-type to application/json in the request headers, but I just get a 500 status code (see screenshot below). All other endpoints of the API are working just fine, but they're expecting "text/plain"...any help is greatly appreciated!

I just setup a simple button to make the POST:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

constructor(private http: HttpClient) { }

ngOnInit() {}

onClickMe( ) {

    // I'VE TRIED ALL THESE DIFFERENT WAYS ALSO

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

        const httpHeaders = new HttpHeaders();
        httpHeaders.append('Content-Type', 'application/json');

        const options = {
            headers: httpHeaders
        }; 
      */

    const httpHeaders = new HttpHeaders().set(
        'Content-Type',
        'application/json'
    );
    const uNameObj = {
        username: "asdf"
    };

    const jsonStr = JSON.stringify(uNameObj);
    let existsCheck: boolean;
    this.http
      .post('http://localhost:8080/myapp/user/username',
            '{"username": "asdf"}',
           {
             observe: 'response',
             headers: httpHeaders
            })
       .subscribe(
           responseData => {
               if (responseData.status === 200) {
                   existsCheck = true;
               } else {
                   existsCheck = false;
               }
           },
           error => {
               console.log('Error with post button', existsCheck);
           }
       );
    }
 }

NO HEADER OPTIONS ADDED WITH CONTENT_TYPE CHANGED IN HEADERS

POSTMAN SCREENSHOT - 200 STATUS CODE: BACKEND API CORS FILTERS

4
  • have you tried: this.http.post('http://localhost:8080/myapp/user/username', jsonStr, and how your Post Action Method looks like? Commented Oct 6, 2019 at 4:11
  • Yeah I tried that. Sorry, I meant to state that. Commented Oct 6, 2019 at 4:18
  • angular.io/guide/http#making-a-post-request use an interface and post uNameObj Commented Oct 6, 2019 at 4:20
  • Hey Andrew, I'm not really sure what you're suggesting Commented Oct 6, 2019 at 4:23

1 Answer 1

1

First of all, for your specific case, you don't really need to do anything extra to set the request Content-Type as application/json. That's something that HttpClient does for you out of the box for most of the cases.

Now as far as your error is concerned, that has something to do with CORS. Since this is an AJAX Request you're making for an API running on a separate PORT(8080) while your Frontend Application is running on a separate port(4200 most probably), the browser would block the request.

To allow, it would need access-control-allow-origin: * in the response headers. This is something that your browser would do by sending an OPTIONS call to the API first.

Since the API doesn't really have access-control-allow-origin: * in the response header, it would be blocked. That's exactly what's happening here.

FIX:

Since this is a POST API and you're running the server on the local, it's safe to assume that you can configure the REST API server to enable CORS.

If it were an express server you could enable CORS on it using the cors middleware.

Here's a Frontend - Sample StackBlitz for your ref.

Here's a Backend - CodeSandbox Sample for your ref.

Sign up to request clarification or add additional context in comments.

16 Comments

Hi @siddAjmera that's part of the thing, the CORS are fine. The PostMan request goes through just fine and I'm able to hit different endpoints that are set as text/plain, it's just this and another endpoint that are set to application/json that I have issues with. If you look at the first error screenshot it seems to be going through as text/plain for the content-type
The API is a Java using Grizzly backend.
I added an additional screenshot showing the CORS in the API
@NoobCoderChick Postman is dev tool and so won’t trigger any cors issue you may have on your backend. The fact you don’t get error for text/plain points to cors as this type is not covered by cors. Read this
@SiddAjmera I accepted your answer, because it is basically the correct response. I figured I'd let you know how I fixe it in case you care haha. I'm not sure why, but my API (Java/Jersey2) was doing something funky when I sent a JSON object. So I now send a json string from the client and let my API consume the string and convert it to a json object I can then use. I'm still not sure why Postman would allow it to work, but something with the browser caused a preflight cors error....Anyways, thank you so much for your help!!!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.