繁体   English   中英

如何以角度 13 从 httpClient POST 读取响应代码

[英]How to read response code from httpClient POST in angular 13

我的后端只用 201 代码回答“OK”。 好吧,我想从角度读取这个 201 代码,但我只能读取响应正文:“OK”。 这是订阅的代码:

this.socialService.postComment(this.contentCode, comment, this.answeredComment.id).subscribe(
      value => {
        console.log(value);
        console.log(value.status);
        console.log(value.headers);
        console.log(value.body);
      }
    );

如您所见,我正在尝试以多种方式读取状态代码,但所有这些都在未定义的控制台中打印,但第一个打印“OK”。 这是postComment代码:

postComment(contentCode: number, comment: string, answeredComment: number): Observable<HttpResponse<string>> {
    
    let params = new HttpParams();
    params = params.append('contentCode', contentCode.toString());
    if(answeredComment != null){
      params = params.append('answer_to', answeredComment.toString());
    }
    const httpOptions = { 
      headers: new HttpHeaders({ 
        'Content-Type': 'application/json'
      }), 
      params: params,
      comment: comment,
      observe: 'response'
    };
    return this.httpClient.post<any>(`${environment.apiBase}/social/comments/postcomment/`, httpOptions);
  }

我想我做错了什么。 如何阅读响应代码?

您正在执行发布请求并且缺少数据,您应该更改它以获取请求或传递一些数据。 你可以简单地尝试改变它:

const data = {};
return this.httpClient.post<any>(`${environment.apiBase}/social/comments/postcomment/`, data, httpOptions);

目前尚不清楚您到底想要实现什么。

  • 预期的响应主体是什么? 空的? 一个东西? 如果有,是什么类型的?
  • 你想在对响应做某事之前检查响应的 statusCode 吗? 如果是这样,检查完reponseCode后你想做什么?
  • Oservable 的 responseType 应该是什么?
  • 你想捕捉http错误代码吗?
  • 您只想返回 statusCode 吗?

您错误地使用post() ,因为您在 httpOptions 中添加了comment ,请在此处阅读更多相关信息。 在这个解决方案中,我将返回响应的 statusCode。 通过此示例,您应该能够实现其他场景。

postComment(
  contentCode: number,
  comment: string,
  answeredComment: number | null
): Observable<number> {
  return this.http
    .post(`${environment.apiBase}/social/comments/postcomment/`, comment, {
      headers: { 'Content-Type': 'application/json' },
      params: {
        contentCode: contentCode.toString(),
        ...(answeredComment !== null && {
          answered_to: answeredComment.toString(),
        }),
      },
      observe: 'response',
    })
    .pipe(
      map((response) => {
        return response.status;
      })
    );
}

如果 POST 调用产生“201 OK”响应,则表示 OK。

然后,我可能会设置另一个对服务器的 GET 调用,以检查该 ID 是否已创建/更新。

如果是,那么我需要获取 GET 返回的记录,并在我的前端实现。 否则,如果您的 BACKEND 是您的,您可以实施更多信息以向您提供更多消息。

检查下面的代码,我主要用于我自己的目的,仅

 // set response code - 400 bad request
http_response_code(400);

// tell the user
echo json_encode(array(
    'passed' => true,
    'Response' => "400 bad request" . "<br>" .
         " !empty(" . "$" . "data->FIELD NAME) is NOT successful."  . "<br>" .
        " Chances are that user has entered Bad Data.",
    'userMessage' => "User creation failed. Please check your data, or try again later or just send message to helpline for support."
));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM