2

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?

3 Answers 3

3

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

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

3 Comments

Thanks, It worked. But how would i combine httpOptions along with the queryParams?
Updated my answer with sample with Accept, since you cannot add header 'Content-Type':'application/json' as that is not what you send :)
True, but originally i was using PUT request, i rolled back to POST for debugging. Now with your solution i can go back to implementing my original code! Thanks again. :)
1

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 Comments

I understand what you're saying, at first i thought that too and changed my function to return this.http.post<any>(this.apiUrl + '/log',{ params: new HttpParams() .set('category', category) .set('value', value) } ) , but still the same error.
I would like to add that your solution was correct the fault lied in my implementation, sorry about that.
its running now, thats all that counts :D
1

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)
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.