我试图使用axois库在我的Vue项目中的laravel项目中调用api 它可以很好地与get请求一起工作,但是当尝试使用post请求时却出现了错误
从原点“ http://localhost:8000/api/”到“ http://localhost:8080”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态< / p>
这是我的Vue代码
axios.post('http://localhost:8000/api/',{id: '1263532984684118016', count: 20}).then(res=>{
console.log(res)
}).catch(error => {
console.log(error)
})
这是我在api.php中的laravel代码
Route::post('/', function (Request $request) {
$response = Twitter::getRters(['id' => "1263532984684118016", 'count' => 20,]);
$body = json_encode($response);
$bodyToObject = json_decode($body, true);
$ids = $bodyToObject['ids'];
$selectedWinners = [];
for($i = 0; $i <3 ; $i++) {
array_push($selectedWinners, $ids[rand(0, count($ids))]);
}
return $selectedWinners;
});
我创建了中间件来处理Cros错误
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
请帮忙。