Angular HTTP POST Request throwing net::ERR_HTTP2_PROTOCOL_ERROR error

最后都变了- 提交于 2020-12-13 07:05:45

问题


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?


回答1:


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




回答2:


Are you missing the request params in your post request?

{params: {categogy: '2', message: .., ...}}

because when I use your link with request params, I get a 200 result. but you are not sending request params to your backend.

send request params with angular or expect a request body in your backend. but I am not familiar with node/express. but it seems like thats whats going wrong.




回答3:


After searching for few hours finally got a solution my issue was when i pass headers to http get or post requests i got the ERR_HTTP2_PROTOCOL_ERROR error i see the issue only if i use angular http and the api works perfect on postman or other online http post tools with headers.

the solution i made is to go to your server side php file (api file) and make sure its only returning a single echo no more than one and check if there is any issue need to be fixed.

this is my code

import { HttpClient , HttpParams, HttpHeaders, HttpErrorResponse} from '@angular/common/http';

  const httpOptions = {
     headers: new HttpHeaders({
     'Content-Type':  'application/json',
     Authorization: 'Your-Api-Key'
   })
   };

   console.log(httpOptions)

   return this.http.get('http://localhost:8080/api.php',httpOptions).subscribe((data)=>{
        console.log(data)
    })


来源:https://stackoverflow.com/questions/58640844/angular-http-post-request-throwing-neterr-http2-protocol-error-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!