weixin_33722405 2016-09-24 11:46 采纳率: 0%
浏览 61

Laravel 5.3 Ajax登录

I'm trying to login my users with ajax with a new Laravel 5.3 project.

I've generated the auth routes, which got added to my web.php:

Auth::routes();

I have a html form with email, and password inputs and the csrf field. Then I also have this javascript file:

$("form.login").submit(function(e) {
    e.preventDefault();

    $.ajax({   
        method: "POST",
        dataType: "json",
        headers: { 
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        },
        data: $("form.login").serialize(),
        url: "/login"
    })
    .done(function(data) {
        console.log(data);
    });
});

When I post it however, this shows up in my network tab: chrome dev tools

It redirects back to the original page, without returning any data.

Why is it doing this? Does 5.3 not give json responses anymore?

  • 写回答

2条回答 默认 最新

  • weixin_33727510 2016-09-28 06:10
    关注

    For explanation about my mistake (the kind of same as op), see the edit history of this post.

    How I solved it

    with a little bit of help from @iSensical

    Inside the app/Exceptions/Handler.php there is a unauthenticated function which, by default, knows if the request expects a json answer with the expectsJson() function.

    The problem didn't came from Laravel by itself. It was, surprisingly, the human factor. I wrote a bad piece of code.

    My ajax request did not used an intuitive header for Laravel.

    I had this:

    $http({
        url     : '{{ route('angular.auth.login.post') }}',
        method  : 'POST',
        data    : $.param($scope.user)+'&x-csrf-token='+CSRF_TOKEN,
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
    [...]
    

    We might have used a bad Content-Type. The correct one was application/json like this:

    headers : { 'Content-Type': 'application/json' }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog