当我们使用laravel进行开发时,尤其是前后端完全分离的时候,因为前端项目运行在自己机器(或者别人机器)的指定端口上,比如localhost:8000,而laravel程序运行在另一个端口,所以是跨域的,由于浏览器的同源策略,跨域请求是不合法的。其实这个问题很好解决,加一个中间件就可以了。新建一个中间件phpartisanmake:middlewareEnableCrossRequestMiddleware书写中间件内容server('HTTP_ORIGIN')?$request->server('HTTP_ORIGIN'):'';$allow_origin=['http://localhost:8000',];如果(in_array($origin,$allow_origin)){$response->header('Access-Control-Allow-Origin',$origin);$response->header('Access-Control-Allow-Headers','Origin,Content-Type,Cookie,X-CSRF-TOKEN,Accept,Authorization,X-XSRF-TOKEN');$response->header('Access-Control-Expose-Headers','Authorization,authenticated');$响应->头er('访问控制允许方法','GET,POST,PATCH,PUT,OPTIONS');$response->header('Access-Control-Allow-Credentials','true');}返回$响应;}}$allow_origin数组变量是你允许跨域的列表,你可以自己修改,在内核文件中注册中间件protected$middleware=[//moreApp\Http\Middleware\EnableCrossRequestMiddleware::class,];在App中添加\Http\Kernel类的$middleware属性,这里注册的中间件属于全局中间件。然后你会发现前端页面已经可以发送跨域请求了。method作为options的请求多一个是正常的,因为浏览器首先要判断服务器是否允许跨域请求。
