这个问题困扰了我一下午,我测试了TP5和Laravel5.4还有原生直接书写。
我在TP5和原生PHP中直接在方法中书写
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers:DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
$data = ['id' => '222','title' => '222','completed' => 'false'];
echo json_encode($data);
我在Laravel5.4中使用的cors扩展书写
Route::post('/msg/create', function (Request $request) {
$data = ['id' => '222','title' => '222','completed' => 'false'];
return $data;
})->middleware('cors:api');
我再vue中是这样访问的
axios.post('http://api_tp.com/index.php/index/index/tp_msg',{}).then(response => {
console.log(response.data);
return false;
});
结果我可以用TP5和原生php的方法访问到数据,laravel中的话会直接卡在OPTIONS请求,提示了跨域的错误。
'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.