Laravel中间件在使用ajax时返回405

时间:2016-11-19 21:51:25

标签: php laravel symfony laravel-5 laravel-routing

我已登录我的网站,我目前所在的网页需要admin中间件。我也从这个页面得到了api电话。此api调用也通过相同的admin中间件,位于api.php文件中(laravel 5.3)。我对网页的请求有效。然而,我在api调用上的中间件返回302将我重定向到login页面。我使用Auth::actingas($user)进行api调用的测试用例也很好。即使页面存在,中间件似乎也没有意识到我已登录。

我还在api/*的例外列表中添加了VerifyCSRF。我该如何解决这个问题?

这是我的routes/web.php文件(我目前所在的网页是manageAdmins

Route::group(['prefix' => 'admin', 'middleware' => ['admin']], function(){
  Route::get('/', 'AdminController@showHome');
  Route::get('categories', 'AdminController@showCategories');
  Route::get('categories/add', 'AdminController@getAddCategories');
  Route::get('manageAdmins', 'AdminController@manageAdmins');

});

我的routes/api.php文件:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

Route::get('categories/{id}/children', 'CategoryController@getChildren');

Route::group(['prefix' => 'admin', 'middleware' => ['web', 'admin']], function() {
    Route::put('makeNormalUserOfAdmin/{id}', 'AdminController@makeNormalUserOfAdmin');
});

这是api调用管理中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard=null)
    {
        if (!(Auth::guard($guard)->check())) {
          return redirect('/login');
        }
        if(!(Auth::user()->is_admin)){
            return redirect('/home');
        }
        return $next($request);
    }
}

这是失败的api调用:

/**
 * delete an admin from the database
 */
function deleteAdmin(id){
    $.ajax({
        method: "PUT",
        url: "/api/admin/makeNormalUserOfAdmin/" + id,
        error: function(data){
            alert('error');
        },
        success: function(data){
            $("table#admins tr#id" + id).fadeOut();
        }
    });
}

最后这是传递的测试用例:

<?php

use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\User;

class MakeNormalUserOfAdminTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * Test the get categories method
     *
     *
     */
    public function testMakeNormalUserOfAdmin()
    {

        $miscalaneousUsers = factory(App\User::class, 20)->create();

        $user = factory(App\User::class)->create([
            'is_admin' => true
        ]);

        $this->actingAs($user)
            ->json("PUT", "api/admin/makeNormalUserOfAdmin/$user->id")
            ->assertResponseOk()
            ->assertResponseStatus(200);

        $this->seeInDatabase('users', [
            'id' => $user->id,
            'name' => $user->name,
            'password' => $user->password,
            'remember_token' => $user->remember_token,
            'updated_at' => $user->updated_at,
            'created_at' => $user->created_at,
            'is_admin' =>  0
        ]);

        $this->dontSeeInDatabase('users', [
            'is_admin' => 1
        ]);

    }
}

1 个答案:

答案 0 :(得分:0)

PHP不处理PUT请求,因此laravel通过发送带有_method=put正文字段的POST来模仿它。因此,为了使您的请求正常工作,您需要添加数据

data: {
    _token: csrfToken,
    _method: 'put'
}

将请求方法更改为POST