php - 传递来自 Laravel 的状态代码未被 Angular http 接收

标签 php angularjs http

我正在构建一个前端 Angular 应用程序和一个单独的 Laravel 5.1 API。我正在通过发布重复的电子邮件地址来测试注册验证。

当它抛出带有状态码的错误时,

返回新的 JsonResponse($errors, 422);

我的 Angular $http 方法根本没有收到响应,因此在 Angular 响应上调用了 success NOR error 方法.

但是,如果我从 JsonResponse 中删除状态代码 422:

return new JsonResponse($errors);

我可以将响应接收到 Angular 中。

我觉得这很奇怪,因为使用状态代码 422 仍然从网络选项卡返回响应,但 Angular 没有收到:

422(不可处理的实体)

回复:email : ["The email already been taken."]

我想从 Laravel 传递状态代码,因为我想要一个非 200 来触发 Angular $http .error 响应。

代码片段:

Angular :

signup: function(params) {
    return $http({
        method: 'POST',
        url: url + ver + '/auth/register',
        data: params,
        cache: true
    });
}

Auth.signup(scope.user).success(function(res){
     console.log(res);
}).error(function(err) {
    alertify.error('There was an error with your login credentials. Please try again');
});

拉拉维尔:

public function postRegister(Request $request)
{
    $validator = $this->validator($request->all());

    if ($validator->fails()) {
        $this->throwValidationException(
            $request, $validator
        );
    }

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->ajax() || $request->wantsJson()) {
        return new JsonResponse($errors, 422);
    }

编辑:我还认为这可能是 Angular error 不是由 422 代码触发的问题。 This说在顶部添加但这并没有解决问题

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

最佳答案

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

https://docs.angularjs.org/api/ng/service/$http

尝试使用 then 代替:

Auth.signup(scope.user).then(function(res) {
    console.log(res);
}, function(err) {
    alertify.error('There was an error with your login credentials. Please try again');
});

关于php - 传递来自 Laravel 的状态代码未被 Angular http 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37581977/

相关文章:

php - 在一个 PHP 文件中运行 2 个 MySQL 更新查询

PHP 获取所有 Twitter 关注者并将他们与好友进行比较

php - 使用 Laravel Migration 添加额外的表

css - 输入标题显示在 Material Design 表单中的输入字段下方

python: urllib.request.urlopen 不起作用

php - Htaccess - Http 身份验证 - 为什么此 block 对我造成 500 错误?

PHP 在数组变量中添加条件(WooCommerce API)

javascript - AngularJS 在第一次 ng-click 时返回 undefined

angularjs - 编写自定义指令以将工具提示添加到 AngularJS (TypeScript) 中的 ng-options

http - Xamarin MvvmCross HTTP请求: How does this work?