Laravel 5.2 ajax登录

时间:2016-03-30 03:58:52

标签: ajax laravel

我对laravel v 5.2有一些问题

我使用ajax post请求,服务器响应201 Ok,返回数据用户,但是当开始重定向到

public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    return view('home');
}

我再次登录登录表单,,,如果我使用刀片表单进行身份验证,请正常工作。

ajax送我                 成功:函数(){

               alert('okey all fine');      

             window.location.href = "/home";     

但/ home页面看不到我的会话或?? :)谢谢

4 个答案:

答案 0 :(得分:0)

请将laravel / framework更新为5.2.27并备份您的Auth\AuthController(如果您进行了任何更改)然后发出php artisan make:auth以使用最新的bug替换现有的laravel生成的auth功能文件固定副本。

看看这是否解决了你的auth会话不是持久性问题

答案 1 :(得分:0)

可能是错误,因为api路由组中有2个缺少的中间件。将以下2个中间件添加到api中间件组,然后将该组添加到API路由

 \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,

答案 2 :(得分:0)

Okey让我看看我的文件

内核

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],


        'api' => [
            'throttle:60,1',

        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFormToken::class,
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
        'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
        'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

    ];
}

路由

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });



});

//Route::get('/register',array('as'=>'newRegister','uses'=>'MailController@index'));

Route::post('/auth', 'MailController@store');

Route::group(['prefix' => 'api', 'middleware' => 'auth:api'], function () {

    Route::resource('note', 'NoteController');
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();    
    Route::get('/backoffice', 'HomeController@home');


});


Route::group(['middleware' => 'web'], function () {
    Route::auth();    
    Route::get('/home', 'LoginController@index');

});

请求

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }



    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

控制器

<?php

namespace App\Http\Controllers;

use Auth;
use Mail;
use Session;
use Redirect;
use App\Http\Requests;
Use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;



Use App\User;

class MailController extends Controller
{
   public function store(LoginRequest $request)
    {


     $credentials = $request->only('email', 'password');

     if (Auth::attempt($credentials)) {

    if (Auth::check()) {


        if (Auth::check()) return Redirect::to('/home');

     }
    }

       return response(['msg' => 'Error'], 401) // 401 Status Code: Forbidden, needs authentication
          ->header('Content-Type', 'application/json');

    }

     public function createRegister(Request $request)

    {
        $user = new User;
        $data['name']=$user->name=$request->username;
        $data['email']=$user->email=$request->email;
        $user->password=bcrypt($request->password);
        $user->remember_token=str_random(100);
        if ($request->password==$request->confirm_password){


        if ($user->save())
        {
            Mail::send('mail.register',['data'=>$data], function($mail) use ($data){
                $mail->to($data['email'],$data['name'])->from('info@ddrw.ru')->subject('Welcome to');
            });
        }}else { return "Password not match";}
        return back();
    }
}

和我的表单javascript

 var form1 = {
            view:"form", id:"log2", width:550, scroll:false,
            elements:[
                {  cols :[
                { view:"text", hidden:true, name:"_token", value:'{{ csrf_token() }}', labelWidth:50, label:"Email" },
                    { view:"text", name:"email", value:'', labelWidth:50, label:"Email" },
                    { view:"text", name:"password", value:'', type:"password", placeholder:"password" },
                    {view:"button",  width:100, label:"login", click:login}
                ]}
            ]
        };

  function login(){
            QW.message("Auth");
            var values = $$("log2").getValues();
            values = JSON.stringify(values);
            console.log(values)
            QW.ajax().sync().headers({'Content-Type':'application/json'}).post("/auth", values, {
                error:function(){
                             QW.alert('Oops');   

                },
                success:function(){




                    QW.alert('Thanks All fine');    

                     //    window.location.href = "/home";   
        }
            });

        }

答案 3 :(得分:0)

我找到了解决方案。

路线问题...会话没有签到我的解决方案......但这是正确的。

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/home', 'HomeController@index');
    Route::get('/redirect', 'SocialAuthController@redirect');
    Route::get('/callback', 'SocialAuthController@callback');
    Route::post('/auth', 'MailController@store');


});


Route::auth();

Route::get('/home', 'HomeController@index');