Created an API with Laravel 5.6 and all endpoints work as expected with Postman. The problems began when i started to develop the Angular 6 app. Since i'm working locally, i began to get CORS errors in Chrome no matter the http method used (httpClient). So i created a middleware in Laravel to process the CORS requests. And everything started to worked as expected, so i thought... Now i'm facing other problems.
I'm using Laravel's default controller actions for the CRUD tasks, so i'm mostly using resource routing (Route::resource). For custom methods i'm using Route::post().
Now, the weird thing is that i'm able to send post request for custom methods (Route::post), but not to resource routes.
Example:
//post requests to custom routes work as expected
Route::post('users/block', 'API\UserController@toggleBlock');
Route::post('users/access', 'API\UserController@sendAccess');
//post requests to resource routes nothing happens
Route::resource('settings', 'API\SettingController');
Route::resource('products', 'API\ProductController');
If i change the routes to the following:
Route::get('settings', 'API\SettingController@index'); //works!
Route::post('settings', 'API\SettingController@store'); //nothing happens!!
Route::post('settings/bazinga', 'API\SettingController@store'); //works!!
So, from what i can tell, i can't use the same URI even thought the http methods are different.
Here is my CORS middleware:
public function handle($request, Closure $next)
{
//apply cors only to api routes
if (Request::segment(1) == 'api') {
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, Authorization, Accept, Cache-Control',
];
if ($request->isMethod("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);
}
} else {
$response = $next($request);
}
return $response;
}
Why is this happening? Is this related to CORS? Since everything works as expected with Postman, this might be related with CORS, right?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire