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

其他-Angular HTTP POST请求抛出net :: ERR_HTTP2_PROTOCOL_ERROR错误

(其他 - Angular HTTP POST Request throwing net::ERR_HTTP2_PROTOCOL_ERROR error)

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

我有自己的API和POST路由,其工作方式如下:

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

});

当我从其他来源发送HTTP POST请求时,服务器响应良好,请单击此处查看示例

类别:“ SOME CAT”

值:“ SOME VAL”

但是当我通过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.');
          }
        });

    }
  }

我收到以下错误。

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

我究竟做错了什么?

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

你的api需要HttpParams,因此你应该将params设置为params而不是body:

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

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

然后将身体设为null

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

这似乎很好用:STACKBLITZ