Warm tip: This article is reproduced from serverfault.com, please click

Angular HTTP POST Request throwing net::ERR_HTTP2_PROTOCOL_ERROR error

发布于 2019-10-31 10:02:25

I have my own API and a POST route working as follows,

Server

//  Handling CORS with a simple lazy CORS
$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});
$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, application/json')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST')
        ->withHeader('Content-Type','application/json')
        ->withHeader('X-Powered-By','Mercurial API');

});

...

$app->post('/api/log', function( Request $request, Response $response){
    
    $category = $request->getParam('category');
    $value = $request->getParam('value');
     
    return logQuery($category, $value, $response);

});

When i am sending a HTTP POST Request from other sources the server is responding fine, Kindly click here to see the example

category:"SOME CAT"

value:"SOME VAL"

But when i sending the same through my Angular App,

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

...

  public putLog(category: string, value: string) {
    //  You can add new argument in header like,
    //  httpOptions.headers = httpOptions.headers.set('Authorization', 'my-new-auth-token');

    const body = JSON.stringify({ category: category, value: value });

    console.log(body);
    return this.http.post<any>(this.apiUrl + '/log', body, httpOptions)
      .subscribe(
        data => {
          console.log('PUT Request is successful.');
        },
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            console.log('Client-side error occured.');
          } else {
            console.log('Server-side error occured.');
          }
        });

    }
  }

i am getting the following error.

{"category":"message","value":"asdasd"}
Server-side error occured.
OPTIONS https://sizilkrishna.000webhostapp.com/api/public/api/log net::ERR_HTTP2_PROTOCOL_ERROR

What am i doing wrong?

Questioner
Mercurial
Viewed
11
AJT82 2019-10-31 19:05:15

Your api expects HttpParams, so you should set your params as params and not body:

const params = new HttpParams().set("category", category).set("value", value);

const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'application/json',
  }),
  params: params
};

and then have body as null:

return this.http
  .post<any>(
    this.apiUrl + "/log",
    null,
    httpOptions
  )
  // .....

That seems to work just fine: STACKBLITZ