使用laravel5.3做接口,前端跨域访问。
当前端发起请求时,浏览器会先发起options请求,就是cors跨域的问题,先是请求一个test.php
,请求是成功的
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: content-type,authorization");
$arr=['1','2'];
echo json_encode($arr);
?>
然后请求laravel5.3的接口,options请求没有返回设定的header
Route::any('/user', function (Request $request) {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: content-type,authorization");
return [$request->user()];
})->middleware('auth:api');
不要直接写在路由内,可以考虑使用中间件,这个应该可以帮到你
http://stackoverflow.com/ques...