代码之家  ›  专栏  ›  技术社区  ›  Carlos Salazar

$request->ajax()在ajax调用时返回false

  •  0
  • Carlos Salazar  · 技术社区  · 6 年前

    我正在用发出Ajax请求 axios 到A laravel controller ,我想用 middleware 检查是否 request 是用做的 ajax 但问题是当我 ajax request, 这个 中间件 投掷 false 总是这样。

    我打这个电话

    axios.post('/api/contact/send', {
        ...
        data : data
    }).then((response) => {
        Do somethings
    }).catch(err => {
        Do somethings
    })
    

    我的API路由

    Route::namespace('Home')->middleware('IsAjaxRequest')->domain(env('HOST'))->group(function(){
        ....
        Route::post('contact/send','ContactController@postContact');
    });
    

    这个 IsAjaxRequest 中间件

    if(!$request->ajax()) {
        abort(403, 'Unauthorized action.');
    }
    return $next($request);
    

    和管制员

    <?php
    
    namespace App\Http\Controllers\Home;
    
    use Illuminate\Http\Request;
    use App\Events\Home\ContactMail;
    use App\Http\Controllers\Controller;
    
    use App\Http\Requests\ContactRequest;
    class ContactController extends Controller
    {
        //
        public function postContact(ContactRequest $request)
        {
    
            $data  = $request->all();
            event(new ContactMail($request->all()));
            return response()->json();
        }
    }
    

    如果我拿出 中间件 ,一切都会好起来的,问题是我检查的时候 $request->ajax() 那个回报 ,我已经在外面检查过了 中间件 直接在 controlelr 但结果是一样的,怎么了?为什么回来 如果是通过Ajax进行的呼叫?

    1 回复  |  直到 6 年前
        1
  •  4
  •   apokryfos    6 年前

    AXIOS不发送 X-Requested-With Laravel查找以确定请求是否为Ajax的头。

    如果你问我,你根本不应该使用或依赖这个头文件,除了(我猜)为了方便从jquery(包括头文件)迁移到基本的laravel样板文件之外。 bootstrap.js 有代码:

    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    

    这可以确保使用AXIOS发出的所有请求都获得这个头文件,但是如果您不使用该文件,则需要在自己的脚本中运行这一行。