将Slim 3 Exception响应传递给Angular应用程序

问题描述 投票:0回答:1

我正在创建一个在后端使用Slim 3 PHP并在前端使用Angular的身份验证系统。到目前为止,我已经设法做到这一点,以便用户可以在前端上填写表格,并向后端发送发布请求,以将该数据插入数据库表。

角寄存器组件:

this.Auth.postUserDetails(username, password).subscribe(data => {
  console.log(data, 'is what we received from the backend:');
  });

角度认证服务:

postUserDetails(username, password) {
    return this.http.post('/api/achievement-forum-api/src/public/register',
      {username, password});
  }

但是在后端,我进行了某种形式的验证,当密码少于8个字符时会产生一些消息,这种形式是扩展PHP的LogicException类的类的形式。

use Throwable;

class InvalidFormData extends \LogicException
{
    public function __construct($message = "Password must be at least 8 characters", $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

}

当密码类的构造函数中验证失败时,抛出此InvalidFormData:

public function __construct(string $tainted_password)
{
    $cleaned_password = filter_var($tainted_password, FILTER_SANITIZE_STRING);

    if ($this->isTooShort($cleaned_password))
    throw new InvalidFormData();

    $this->password = $cleaned_password;
}

然后,在控制器类中,我们尝试注册用户,但是如果捕获到InvalidFormData异常,则会提取产生的消息。

public function registerUser($request, $response)
{
    $tainted_username = $request->getParsedBody()['username'];
    $tainted_password = $request->getParsedBody()['password'];

    try
    {
        $this->authenticationService->registerUser($tainted_username, $tainted_password);
    }

    catch(InvalidFormData $e)
    {
        var_dump($e→getMessage()); //shows the message in the browsers console
    }
}

问题:

我想做的是将此消息传递回Angular前端,并在表单上显示它,以便用户能够查看为什么他们的验证失败。

我已经阅读了Slim 3的响应文档,但是不确定是否必须将这条消息作为Slim响应发送回去,如果可以,我该如何在Angular中捕获它?我的第一个想法是,可能需要在angular中获取请求,以获取消息,但是我敢肯定,在原始发布请求中有一种方法可以做到这一点。

我已经阅读了一些Angular文档,似乎我需要在subscribe方法中做一些事情,但是我不确定是什么。

希望有人可以向我展示一些此过程的代码示例。如何创建包含消息的Slim 3响应,以及如何在Angular中捕获此响应?

php angular validation response slim-3
1个回答
0
投票

src/routes.php中设置:

$app->post( '/api/achievement-forum-api/src/public/register', function( Request $request, Response $response, array $args ) {
    $body = $request->getParsedBody();
    // probably $body = [ "username" => "user name", "password" => "pass word" ]
    /* Do validation stuff here */
    /* Depending of your validation results, set $status = something like 0 or 1... */
    /* Depengind of your $status, set $message = "string to be displayed" */
    /* Need to return data? $data = [ ... ] */
    return $response->withJson( [ "status" => $status, "message" => $message, "data" => $data ] );
} );

响应布局的灵感来自Instagram API(https://www.instagram.com/developer/endpoints/

[几年来我一直没有与Angular联系,但我认为您必须执行postUserDetails( params, here ).map(res=> res.json())之类的操作或所用Angular版本中的另一个“ responseHandler”方法。

我在我的项目中经常用fetch APIhttps://developer.mozilla.org/pt-BR/docs/Web/API/Fetch_API/Using_Fetch)或axioshttps://github.com/axios/axios)来做

© www.soinside.com 2019 - 2024. All rights reserved.