Laravel添加ajax可跨域访问

  • 发布时间:2017-09-26 18:09:59
  • 作者:风萧萧兮易水寒
  • 标签:laravel跨域

添加一个中间件:

php artisan make:middleware Csrf


在Htpp/Kernel中注册中间件

'csrf' => \App\Http\Middleware\Csrf::class,


再route中引入web与csrf两个中间件

中间件处理方式为:

<?php

namespace App\Http\Middleware;

use Closure;

class Csrf
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
$response = $next($request);
//$response->header('Access-Control-Allow-Origin', 'http://192.168.40.234:8080');
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
return $response;
    }
}



这样就可以允许跨域ajax访问了。




前端ajax还需要设置

xhrFields: {
    withCredentials: true
},
crossDomain: true