【问题标题】:Angular HTTP POST Request throwing net::ERR_HTTP2_PROTOCOL_ERROR errorAngular HTTP POST 请求抛出 net::ERR_HTTP2_PROTOCOL_ERROR 错误
【发布时间】:2020-12-05 22:59:00
【问题描述】:

我有自己的 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 请求时,服务器响应良好,Kindly click here to see the example

类别:“某只猫”

值:“某些值”

但是当我通过我的 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

我做错了什么?

【问题讨论】:

    标签: angular post http-headers slim


    【解决方案1】:

    您的 api 需要 HttpParams,因此您应该将参数设置为参数而不是正文:

    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

    【讨论】:

    • 谢谢,它成功了。但是我如何将 httpOptions 与 queryParams 结合起来?
    • Accept 的示例更新了我的答案,因为您不能添加标题'Content-Type':'application/json',因为这不是您发送的内容:)
    • 是的,但最初我使用PUT 请求,我回滚到POST 进行调试。现在有了你的解决方案,我可以回去实现我的原始代码了!再次感谢。 :)
    【解决方案2】:

    您是否缺少发布请求中的请求参数?

    {参数:{类别:'2',消息:..,...}}

    因为当我将您的链接与请求参数一起使用时,我得到 200 结果。但您没有向后端发送请求参数。

    发送带有角度的请求参数或期望后端的请求正文。但我不熟悉节点/快递。但似乎这就是问题所在。

    【讨论】:

    • 我明白你在说什么,一开始我也是这么想的,把我的功能改成了return this.http.post&lt;any&gt;(this.apiUrl + '/log',{ params: new HttpParams() .set('category', category) .set('value', value) } ),但还是同样的错误。
    • 我想补充一点,您的解决方案是正确的,我的实施存在错误,对此感到抱歉。
    • 它现在正在运行,仅此而已:D
    【解决方案3】:

    找了几个小时终于找到了解决办法 我的问题是当我将标头传递给 http get 或 post 请求时出现 ERR_HTTP2_PROTOCOL_ERROR 错误 只有当我使用 angular http 并且 api 在邮递员或其他带有标题的在线 http 发布工具上完美运行时,我才会看到这个问题。

    我所做的解决方案是转到您的服务器端 php 文件(api 文件) 并确保它只返回一个不超过一个的回声,并检查是否有任何问题需要修复。

    这是我的代码

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

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 2015-12-31
      • 1970-01-01
      • 2015-11-18
      • 2019-11-15
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多